题目实际意思,就是找两篇文章中的“最多公共单词”——其实可以把它转换成最长公共子序列问题,只是这里的序列的元素不是字母而是单词罢了。
另外,此题主要是考察LCS的形成路径,因此需要一个数组记录这个路径,这里用的是二维的字符数组dir[][],其中'1''2''3'分别表示斜向上,向左和向上。具体原理可以看算法导论的动态规划的最长公共子序列那一篇的内容,写得非常好。
以下是详细代码:
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
const int M=32,N=105;
char s1[N][M],s2[N][M];
char s[M];
int len1,len2;
int c[N][N];
char dir[N][N],stack[N][M];
char ch;
void LCS()
{
int i,j;
for(i=1;i<=len1;i++)
{
for(j=1;j<=len2;j++)
{
if(strcmp(s1[i],s2[j])==0)
{
c[i][j]=c[i-1][j-1]+1;
dir[i][j]='1';
}
else
{
if(c[i-1][j]>=c[i][j-1])
{
c[i][j]=c[i-1][j];
dir[i][j]='2';
}
else
{
c[i][j]=c[i][j-1];
dir[i][j]='3';
}
}
}
}
}
int main()
{
while(scanf("%s",s)==1)
{
int i=1,j=1;
int top=0;
strcpy(s1[i++],s);
while(1)
{
scanf("%s",s1[i]);
if(s1[i][0]=='#') break;
i++;
}
len1=i-1;
while(1)
{
scanf("%s",s2[j]);
if(s2[j][0]=='#') break;
j++;
}
len2=j-1;
LCS();
i=len1;j=len2;
while(dir[i][j]!='/0')
{
int p,q;
p=i;q=j;
if(dir[i][j]=='1') p-=1,q-=1;
else if(dir[i][j]=='2') p-=1;
else if(dir[i][j]=='3') q-=1;
if(c[i][j]!=c[p][q]) strcpy(stack[top++],s1[i]);
i=p;
j=q;
}
for(i=top-1;i>=0;i--)
printf("%s ",stack[i]);
printf("/n");
}
return 0;
}