NYOJ 17 单调递增最长子序列

本文介绍了一种解决最长递增子序列问题的经典算法,并通过动态规划实现了对多个字符串的处理,提供了完整的代码示例及调试过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


单调递增最长子序列

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

很经典的题目   参考的 http://blog.youkuaiyun.com/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 5
7

贴出最终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);
  }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值