题目大意:求出两个串的公共子序列的长度
LCS的入门题,读懂题了直接模板就可以
#include <iostream> #include <cstring> using namespace std; const int N=1000; int a[N][N]; int LCS(const char *s1, const char *s2) {// s1:0...m, s2:0...n int m = strlen(s1), n = strlen(s2); int i, j; a[0][0] = 0; for( i=1; i <= m; ++i ) a[i][0] = 0; for( i=1; i <= n; ++i ) a[0][i] = 0; for( i=1; i <= m; ++i ) for( j=1; j <= n; ++j ){ if(s1[i-1]==s2[j-1]) a[i][j] = a[i-1][j-1]+1; else if(a[i-1][j]>a[i][j-1])a[i][j]= a[i-1][j]; else a[i][j] = a[i][j-1]; } return a[m][n]; } int main() { char s1[N], s2[N]; while(cin>>s1>>s2) cout<<LCS(s1, s2)<<endl; return 0; }
HDU1159 && POJ1458 Common Subsequence (LCS模版题)
原文地址:http://blog.csdn.net/wangxinxin_/article/details/45101885