您的位置:首页 > 其它

uva-531 Compromise

2016-05-06 17:20 411 查看
题目链接(复制过来好难看)

题目大意:

两个人写下一段话,让你寻找他们两个的最长公共的单词序列。

思路:

只需要把最长公共子序列换成存储单词就可以

代码:

#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
char a[105][35];
char b[105][35];
int dp[105][105];
int path[105];
int main()
{
char str[35];
int l1,l2;
while(scanf("%s",a[1])!=EOF)
{
l1=2;
while(scanf("%s",str))
{
if(strcmp(str,"#")==0)
break;
strcpy(a[l1++],str);
}
l2=1;
while(scanf("%s",str))
{
if(strcmp(str,"#")==0)
break;
strcpy(b[l2++],str);
}
memset(dp,0,sizeof(dp));
for(int i=1; i<l1; i++)
{
for(int j=1; j<l2; j++)
{
if(strcmp(a[i],b[j])==0) // 判断相等
{
dp[i][j]=dp[i-1][j-1]+1;
}
else
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
int ans=dp[l1-1][l2-1];
int i=l1-1,j=l2-1;
int k=0;
while(dp[i][j]) //算出路径
{
if(dp[i][j]==dp[i-1][j])
i--;
else if(dp[i][j]==dp[i][j-1])
j--;
else
{
path[k++]=i;
i--;
j--;
}
}
for(int i=k-1; i>0; i--)//输出
printf("%s ",a[path[i]]);
printf("%s\n",a[path[0]]);

}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: