最长公共子序列
注意从下标1开始存
#include <iostream> #include <cstdio> #include <cstring> using namespace std; #define SZ 1005 int dp[SZ][SZ]; int main() { char s1[SZ], s2[SZ], tmp[SZ]; s1[0] = s2[0] = ‘0‘; while(scanf("%s", s1 + 1) != EOF) { scanf(" %s", s2 + 1); memset(dp, 0, sizeof(dp)); int len1 = strlen(s1); int len2 = strlen(s2); for(int i = 0; i <= len1; i++) { for(int j = 0; j <= len2; j++) { if(i == 0 || j == 0) dp[i][j] = 0; else if(s1[i] == s2[j]) dp[i][j] = dp[i - 1][j - 1] + 1; else dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]); } } printf("%d\n", dp[len1][len2] - 1); } return 0; }