时间限制:3000 ms | 内存限制:65535 KB
难度:3
- 描述
- 咱们就不拐弯抹角了,如题,需要你做的就是写一个程序,得出最长公共子序列。
tip:最长公共子序列也称作最长公共子串(不要求连续),英文缩写为LCS(Longest Common Subsequence)。其定义是,一个序列 S ,如果分别是两个或多个已知序列的子序列,且是所有符合此条件序列中最长的,则 S 称为已知序列的最长公共子序列。
- 输入
- 第一行给出一个整数N(0<N<100)表示待测数据组数
接下来每组数据两行,分别为待测的两组字符串。每个字符串长度不大于1000. - 输出
- 每组测试数据输出一个整数,表示最长公共子序列长度。每组结果占一行。
- 样例输入
-
2 asdf adfsd 123abc abc123abc
- 样例输出
-
3 6
View Code1 #include<iostream>
2 #include<cstdio>
3 #include<cstring>
4 #define max(a,b) (a>b? a:b)
5 #define Max 1010
6 using namespace std;
7 char ch1[Max],ch2[Max];
8 int d[Max][Max];
9 int dp(int i,int j)
10 {
11 int ans=0;
12 if(i<0||j<0)
13 return 0;
14 if(d[i][j]!=-1)
15 return d[i][j];
16 if(ch1[i]==ch2[j])
17 ans=dp(i-1,j-1)+1;
18 else
19 ans=max(dp(i-1,j),dp(i,j-1));
20 return d[i][j]=ans;
21 }
22 int main()
23 {
24 int t,n,m;
25 cin>>t;
26 while(t--)
27 {
28 memset(d,-1,sizeof(d));
29 scanf("%s%s",ch1,ch2);
30 n=strlen(ch1);m=strlen(ch2);
31 cout<<dp(n-1,m-1)<<endl;
32 }
33 return 0;
34 }