想看更多的解题报告: http://blog.csdn.net/wangjian8006/article/details/7870410
转载请注明出处:http://blog.csdn.net/wangjian8006
题目大意:给出两篇文章,文章里面由一个一个单词构成,每个单词由空格隔开,文章以#作为结束,输出两篇文章的最长的相似句子,句子的答案可能有多种情况,每个输出之后有个换行符。
解题思路:题目类型和最长公共子序列是一样的,只不过这里将最长子序列的字符改成了一个单词。但是输出的时候需要注意,就是要将每次的决策给记录下来,方便输出的时候用,每次输出的时候是当他们相等的时候决策就输出。
#include <iostream>
#include <string.h>
#include <memory.h>
using namespace std;
#define MAXV 110
#define MAXN 35
char stemp[MAXN];
char s1[MAXV][MAXN];
char s2[MAXV][MAXN];
int len1,len2,dp[MAXV][MAXV],p[MAXV][MAXV],pos[MAXV],sum;
int max(int i,int j,int a,int b,int c){
if(a>b && a>c){
p[i][j]=1; //将其决策记录下来
return a;
}
if(b>a && b>c){
p[i][j]=2;
return b;
}
p[i][j]=3;
return c;
}
int same(int x,int y){
if(!strcmp(s1[x],s2[y])) return 1;
return 0;
}
void print(int i,int j){
if(p[i][j]==1){
pos[sum++]=i-1;
print(i-1,j-1);
}else if(p[i][j]==2)
print(i-1,j);
else if(p[i][j]==3)
print(i,j-1);
}
int main(){
int i,j,t;
// Input //
while(~scanf("%s",stemp)){
len1=len2=0;
strcpy(s1[len1++],stemp);
while(1){
scanf("%s",stemp);
if(!strcmp(stemp,"#")){
break;
}
strcpy(s1[len1++],stemp);
}
while(1){
scanf("%s",stemp);
if(!strcmp(stemp,"#")){
break;
}
strcpy(s2[len2++],stemp);
}
// DP //
memset(dp,0,sizeof(dp));
memset(p,0,sizeof(p));
for(i=1;i<=len1;i++)
for(j=1;j<=len2;j++){
dp[i][j]=max(i,j,dp[i-1][j-1]+same(i-1,j-1),dp[i-1][j],dp[i][j-1]);
}
// Output //
sum=0;
print(len1,len2);
for(i=sum-1;i>=0;i--) printf("%s ",s1[pos[i]]);
printf("\n");
}
return 0;
}