NYOJ 17 单调递增最长子序列

来源:互联网 发布:淘宝嘉年华英伦休闲鞋 编辑:程序博客网 时间:2024/06/05 10:08


单调递增最长子序列

时间限制:3000 ms  |  内存限制:65535 KB
难度:4
描述
求一个字符串的最长递增子序列的长度
如:dabdbf最长递增子序列就是abdf,长度为4
输入
第一行一个整数0<n<20,表示有n个字符串要处理
随后的n行,每行有一个字符串,该字符串的长度不会超过10000
输出
输出字符串的最长递增子序列的长度
样例输入
3aaaababcabklmncdefg
样例输出
137

很经典的题目   参考的 http://blog.csdn.net/sjf0115/article/details/8715672

用动态规划做的 时间复杂度n²



讲的很棒 一开始没有理解aj < ai && j < i这个限制条件 于是写出了这个代码

#include<stdio.h>#include<string.h>int main() {  char s[10005];  int n, len, dp[10005];  scanf("%d", &n);  while(n--) {    int max = 0;    scanf("%s", s);    len = strlen(s);    for(int i = 0; i < len; i++) {      dp[i] = 1;      for(int j = 0; j < i; j++)        if(s[i] > s[j])           dp[i] = dp[j]+1;      printf("遍历第%d次结果:", i+1);      for(int i = 0; i < strlen(s); i++)        printf("%d ", dp[i]);      printf("\n");    }    for(int i = 0; i < len; i++)      if(dp[i] > max)        max = dp[i];    printf("%d\n", max);  }}

再遍历中发现了错误

测试了 一组数据 abcdabetawe

       a b c d a b e t a w e遍历第1次结果:1 0 0 0 0 0 0 0 0 0 0遍历第2次结果:1 2 0 0 0 0 0 0 0 0 0遍历第3次结果:1 2 3 0 0 0 0 0 0 0 0遍历第4次结果:1 2 3 4 0 0 0 0 0 0 0遍历第5次结果:1 2 3 4 1 0 0 0 0 0 0遍历第6次结果:1 2 3 4 1 2 0 0 0 0 0遍历第7次结果:1 2 3 4 1 2 3 0 0 0 0遍历第8次结果:1 2 3 4 1 2 3 4 0 0 0遍历第9次结果:1 2 3 4 1 2 3 4 1 0 0遍历第10次结果:1 2 3 4 1 2 3 4 1 2 0遍历第11次结果:1 2 3 4 1 2 3 4 1 2 2
更新大小时应该考虑dp[i] 和 1+dp[j]之间的大小关系

正确的遍历结果应该是

       a b c d a b e t a w e遍历第1次结果:1 0 0 0 0 0 0 0 0 0 0遍历第2次结果:1 2 0 0 0 0 0 0 0 0 0遍历第3次结果:1 2 3 0 0 0 0 0 0 0 0遍历第4次结果:1 2 3 4 0 0 0 0 0 0 0遍历第5次结果:1 2 3 4 1 0 0 0 0 0 0遍历第6次结果:1 2 3 4 1 2 0 0 0 0 0遍历第7次结果:1 2 3 4 1 2 5 0 0 0 0遍历第8次结果:1 2 3 4 1 2 5 6 0 0 0遍历第9次结果:1 2 3 4 1 2 5 6 1 0 0遍历第10次结果:1 2 3 4 1 2 5 6 1 7 0遍历第11次结果:1 2 3 4 1 2 5 6 1 7 57

贴出最终AC代码

#include<stdio.h>#include<string.h>int main() {  char s[10005];  int n, len, dp[10005];  scanf("%d", &n);  while(n--) {    int max = 0;    scanf("%s", s);    len = strlen(s);    for(int i = 0; i < len; i++) {      dp[i] = 1;      for(int j = 0; j < i; j++)        if(s[i] > s[j] && dp[i] < 1+dp[j])           dp[i] = dp[j]+1;        /*        这里if也可以写成        if(a[i] > a[j]) dp[i] = max(dp[i], dp[j]+1);        */    }    for(int i = 0; i < len; i++)      if(dp[i] > max)        max = dp[i];    printf("%d\n", max);  }}


原创粉丝点击