【題目】
【思路】
最長公共子序列的元素變成了單詞,算法依然相同。最後輸出子序列時,只需根據ans數組從後往前索引,遇到序列元素時就將其入棧,最後出棧輸出。
【代碼】
#include <stdio.h>
#include <string.h>
#define size 150
#define max(x,y) x>y? x:y
int main()
{
char s[31], a[size][31], b[size][31];
int x,y,i,j,total,str[size],ans[size][size];
for (i=0;i<size;i++) {ans[i][0]=0; ans[0][i]=0;}
while (scanf("%s",s)!=EOF)
{
x=-1; y=-1;
while (strcmp(s,"#")!=0) {strcpy(a[++x],s); scanf("%s",s);}
scanf("%s",s);
while (strcmp(s,"#")!=0) {strcpy(b[++y],s); scanf("%s",s);}
for (i=1;i<=x+1;i++)
for (j=1;j<=y+1;j++)
if (strcmp(a[i-1],b[j-1])==0) ans[i][j]=ans[i-1][j-1]+1;
else ans[i][j]=max(ans[i-1][j],ans[i][j-1]);
total=ans[x+1][y+1];
while (i>0 && j>0)
if (strcmp(a[i-1],b[j-1])==0) {str[total--]=i-1; i--; j--;}
else if (ans[i-1][j]>ans[i][j-1]) i--; else j--;
for (i=1;i<ans[x+1][y+1];i++) printf("%s ",a[str[i]]);
printf("%s\n",a[str[ans[x+1][y+1]]]);
}
return 0;
}