注意与最长公共子序列的不同
还是对状态的定义不是很了解
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int maxn = 100 + 10; char line1[maxn]; char line2[maxn]; int d[maxn][maxn]; int vis[maxn][maxn]; int dp(int pos1,int pos2) { if(pos1 == 0 || pos2 == 0) return 0; if(vis[pos1][pos2]) { return d[pos1][pos2]; } vis[pos1][pos2] = 1; int ans = 0; if(line1[pos1] == line2[pos2]) { ans = dp(pos1 - 1,pos2 - 1) + 1; d[pos1][pos2] = ans; return ans; } else { d[pos1][pos2] = 0; return 0; } } int main() { freopen("input.txt","r",stdin); scanf("%s",line1 + 1); scanf("%s",line2 + 1); int len1 = strlen(line1 + 1); int len2 = strlen(line2 + 1); for(int i = len1;i > 0;i--) { for(int j = len2;j > 0;j--) { dp(i,j); } } int Max = 0; for(int i_0 = 1;i_0 <= len1;i_0++) { for(int j = 1;j <= len2;j++) { Max = __max(Max,d[i_0][j]); } } printf("%d",Max); return 0; }