Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 6766 | Accepted: 3023 | Special Judge |
Description
Therefore the German government requires a program for the following task:
Two politicians each enter their proposal of what to do. The computer then outputs the longest common subsequence of words that occurs in both proposals. As you can see, this is a totally fair compromise (after all, a common sequence of words is something what both people have in mind).
Your country needs this program, so your job is to write it for us.
Input
Each test case consists of two texts. Each text is given as a sequence of lower-case words, separated by whitespace, but with no punctuation. Words will be less than 30 characters long. Both texts will contain less than 100 words and will be terminated by a line containing a single '#'.
Input is terminated by end of file.
Output
Sample Input
die einkommen der landwirte sind fuer die abgeordneten ein buch mit sieben siegeln um dem abzuhelfen muessen dringend alle subventionsgesetze verbessert werden # die steuern auf vermoegen und einkommen sollten nach meinung der abgeordneten nachdruecklich erhoben werden dazu muessen die kontrollbefugnisse der finanzbehoerden dringend verbessert werden #
Sample Output
die einkommen der abgeordneten muessen dringend verbessert werden
题目链接:http://poj.org/problem?id=2250
题目大意:求出两段文字中最大公共单词序列,最大公子序列LCS问题。
解题思路:LCS模板:dp[i][j]记录前a[i]和前b[j]的最大公共子序列长度。若要记录下子序列,需要数组path[i][j];
分为三种情况:1.a[i-1]==b[j-1] : dp[i][j]=dp[i-1][j-1]+1,path[i][j]=0;
2.dp[i-1][j]>dp[i][j-1] : dp[i][j]=dp[i-1][j] ,path[i][j]=1;
3.dp[i][j-1]>dp[i-1][j] : dp[i][j]=dp[i][j-1] ,path[i][j]=-1;
ans[i]数组记录子序列,path[i][j]=0: ans[cnt++]=a[i];
path[i][j]=1: i--;
path[i][j]=-1: j--;
代码如下:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
string a[105],b[105];
string ans[105];
int path[105][105],dp[105][105];
int la,lb,t,l;
void get(int i,int j)
{
if(!i||!j)
return;
if(path[i][j]==0)
{
get(i-1,j-1);
ans[l++]=a[i-1];
}
else if(path[i][j]==1)
get(i-1,j);
else
get(i,j-1);
}
int main()
{
la=lb=t=l=0;
string s;
memset(path,0,sizeof(path));
memset(dp,0,sizeof(dp));
while(cin>>s)
{
if(t==0)
{
a[la++]=s;
while(cin>>s&&s!="#")
a[la++]=s;
t=1;
continue;
}
if(t==1)
{
b[lb++]=s;
while(cin>>s&&s!="#")
b[lb++]=s;
}
for(int i=1;i<=la;i++)
for(int j=1;j<=lb;j++)
{
if(a[i-1]==b[j-1])
{
dp[i][j]=dp[i-1][j-1]+1;
path[i][j]=0;
}
else if(dp[i-1][j]>dp[i][j-1])
{
dp[i][j]=dp[i-1][j];
path[i][j]=1;
}
else
{
dp[i][j]=dp[i][j-1];
path[i][j]=-1;
}
}
get(la,lb);
for(int i=0;i<l-1;i++)
cout<<ans[i]<<" ";
cout<<ans[l-1]<<endl;
la=lb=l=t=0;
memset(dp,0,sizeof(dp));
memset(path,0,sizeof(path));
}
return 0;
}