NYOJ 36 最长公共子序列 (还是dp)

这个好多算法书上都有,不仅限于《算法导论》


时间限制:3000 ms  |  内存限制:65535 KB

难度:3

  • 描写叙述

  • 咱们就不拐弯抹角了,如题。须要你做的就是写一个程序,得出最长公共子序列。
    tip:最长公共子序列也称作最长公共子串(不要求连续),英文缩写为LCS(Longest Common Subsequence)。

    其定义是。一个序列 S ,假设各自是两个或多个已知序列的子序列,且是全部符合此条件序列中最长的。则 S 称为已知序列的最长公共子序列。

    • 输入

    • 第一行给出一个整数N(0<N<100)表示待測数据组数
      接下来每组数据两行,分别为待測的两组字符串。

      每一个字符串长度不大于1000.

    • 输出

    • 每组測试数据输出一个整数,表示最长公共子序列长度。每组结果占一行。

    • 例子输入

    • 2
      asdf
      adfsd
      123abc
      abc123abc
    • 例子输出

    • 3


#include<iostream>
#include<cstring>
#include <string>
 
using namespace std;
 
int a[1010][1010];
 
int max(int x, int y)
{
    return x>y ?

x : y; } int main() { int test,i,j,k,len1,len2,lcs; string s1,s2; cin>>test; while(test--) { cin>>s1>>s2; len1=s1.length(); len2=s2.length(); memset(a,0,sizeof(a)); lcs=0; for(i=1;i<len1+1;i++) { for(j=1;j<len2+1;j++) { if(s1[i-1]==s2[j-1]) a[i][j]=a[i-1][j-1]+1; else a[i][j]=max(a[i][j-1],a[i-1][j]); if(a[i][j]>lcs) lcs=a[i][j]; } } cout<<lcs<<endl; } return 0; }



原文地址:https://www.cnblogs.com/zhchoutai/p/7261270.html