uva-531 Compromise
제목 대의:
두 사람이 다음 단락을 쓰면 두 사람의 가장 긴 공통된 단어 서열을 찾을 수 있다.
아이디어:
가장 긴 공통 서열을 메모리 단어로 바꾸면 돼요.
코드:
#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
",a[path[0]]);
}
return 0;
}