Uva-531-Compromise

来源:互联网 发布:知天下图片 编辑:程序博客网 时间:2024/06/14 04:15

这个题是求字符串的LCS,最后需要输出最长字符串子串

比较简单吧,写个递归进行输出

代码:

#include<cstdio>#include<cstring>#include<iostream>using namespace std;const int maxn=111;char stra[maxn][50],strb[maxn][50];int n,m,dp[maxn][maxn],p[maxn][maxn];bool first;void OutPut(int x,int y){    if(x<=0||y<=0)return;    if(p[x][y]==0)    {OutPut(x-1,y-1);if(!first){    printf("%s",stra[x]);    first=1;}else    printf(" %s",stra[x]);    }    else if(p[x][y]==1)OutPut(x,y-1);    elseOutPut(x-1,y);}int main(){    while(scanf("%s",stra[1])!=EOF)    {n=2,m=1;memset(dp,0,sizeof(dp));while(1){    scanf("%s",stra[n]);    if(stra[n][0]=='#')break;    n++;}while(1){    scanf("%s",strb[m]);    if(strb[m][0]=='#')break;    m++;}for(int i=1;i<n;i++)    for(int j=1;j<m;j++)    {if(!strcmp(stra[i],strb[j])){    dp[i][j]=dp[i-1][j-1]+1;    p[i][j]=0;}else{    if(dp[i][j-1]>dp[i-1][j])    {dp[i][j]=dp[i][j-1];p[i][j]=1;    }    else    {dp[i][j]=dp[i-1][j];p[i][j]=2;    }}    }first=0;OutPut(n-1,m-1);printf("\n");    }    return 0;}