http://acm.pku.edu.cn/JudgeOnline/problem?id=2250 题目大意:给你两段话,叫你找出它们最长公共子序列 解题思路:LCS,只是字母换单词罢了 #include <stdio.h> #include <string.h> struct words { char s[35]; }a[105],b[105]; int dp[105][105]; int LCS(int len1,int len2) { int i,j,len = 0; memset(dp,0,sizeof(dp)); for (i=1;i<=len1;i++) { for (j=1;j<=len2;j++) { if (strcmp(a[i-1].s,b[j-1].s)==0) dp[i][j] = dp[i-1][j-1]+1; else dp[i][j] = dp[i-1][j]>dp[i][j-1]?dp[i-1][j]:dp[i][j-1]; } } return dp[len1][len2]; } void OutPut(int i,int j) { if(i==0||j==0) return; if (!strcmp(a[i-1].s,b[j-1].s)) { OutPut(i-1,j-1); printf("%s ",a[i-1].s); } else if(dp[i-1][j]>dp[i][j-1]) OutPut(i-1,j); else OutPut(i,j-1); } int main() { int len1,len2; char tem[35]; strcpy(a[0].s,"1"); strcpy(b[0].s,"2"); while (scanf("%s",tem)!=EOF) { strcpy(a[1].s,tem); len1 = len2 = 1; while (scanf("%s",tem),strcmp(tem,"#")!=0) strcpy(a[++len1].s,tem); while (scanf("%s",tem),strcmp(tem,"#")!=0) strcpy(b[len2++].s,tem); if(LCS(len1+1,len2)) { OutPut(len1+1,len2); printf("/n"); } } return 0; }