最长公共子序列
时间限制: 3000 ms | 内存限制:65535 KB
难度: 3
- 描述
- 咱们就不拐弯抹角了,如题,需要你做的就是写一个程序,得出最长公共子序列。 tip:最长公共子序列也称作最长公共子串(不要求连续),英文缩写为LCS(Longest Common Subsequence)。其定义是,一个序列 S ,如果分别是两个或多个已知序列的子序列,且是所有符合此条件序列中最长的,则 S 称为已知序列的最长公共子序列。
- 输入
- 第一行给出一个整数N(0<N<100)表示待测数据组数 接下来每组数据两行,分别为待测的两组字符串。每个字符串长度不大于1000. 输出
- 每组测试数据输出一个整数,表示最长公共子序列长度。每组结果占一行。 样例输入
-
2asdfadfsd123abcabc123abc
样例输出 -
36
我的弱弱的代码:
#include#include #include #include using namespace std;const int INF=0x7fffffff;const int N=1005;char s1[N],s2[N];int dp[N][N];int main(){ //freopen("D:\\input.in","r",stdin); //freopen("D:\\output.out","w",stdout); int n; scanf("%d",&n); for(int i=0;i
一位coder的代码,加了空间优化:
#include#include char s1[1001], s2[1001];int dp[1001], t, old, tmp;int main(){ scanf("%d", &t); getchar(); while(t--){ gets(s1); gets(s2); memset(dp, 0, sizeof(dp)); int lenS1=strlen(s1), lenS2=strlen(s2); for(int i=0; i dp[j])dp[j]=dp[j-1]; old = tmp; } } printf("%d\n", dp[lenS2-1]); } return 0;}
另一位牛人写的代码,加了时间优化,足足缩短了10倍的时间消耗:
#include#include #include #include #include using namespace std;int n,m;const int CHAR = 256;const int maxn = 1010;int ans[maxn*maxn];int dp[maxn*maxn];char S[maxn];vector v[CHAR];int er(int l,int r,int x){ while(l<=r) { int mid = (l+r)/2; if( ans[mid] >= x ) r = mid - 1; else l = mid + 1; } return l;}int main(){ scanf("%d",&n); while( n-- ) { for(int i=0 ; i =0 ; i-- ) { v[ S[i] ].push_back(i); ///S[i]字符在字符串对应的位置 ///cout << S[i] << " " << v[ S[i] ].size() << endl; } int x = 0; scanf("%s",S); l = strlen(S); for(int i=0 ; i