您的位置:首页 > 其它

UVa:531 Compromise

2013-09-02 15:35 393 查看
还是LCS的题,只不过单个字符换成了单词。

一开始没有注意多组测试数据WA了1次。



递归实现输出路径。



#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
string a[101],b[101];
int dp[101][101],path[101][101];
bool fir;
void Traversal(int i,int j)
{
    if(i<=0||j<=0) return ;
    if(path[i][j]==7)
    {
        Traversal(i-1,j-1);
        if(fir==true)
            cout<<" "<<a[i];
        else
        {
            cout<<a[i];
            fir=true;
        }
    }
    else if (path[i][j]==4)
        Traversal(i-1,j);
    else if (path[i][j]==8)
        Traversal(i,j-1);
}
int main()
{
    while(cin>>a[1])
    {
        memset(dp,0,sizeof(dp));
        memset(path,0,sizeof(path));
        int n1=2,n2=1;
        if(a[1][0]!='#')
        {
            while(cin>>a[n1]&&a[n1][0]!='#') n1++;
        }
        while(cin>>b[n2]&&b[n2][0]!='#') n2++;
        for(int i=1; i<n1; ++i)
            for(int j=1; j<n2; ++j)
                if(a[i]==b[j])
                {
                    dp[i][j]=dp[i-1][j-1]+1;
                    path[i][j]=7;
                }
                else
                {
                    if(dp[i-1][j]>dp[i][j-1])
                    {
                        dp[i][j]=dp[i-1][j];
                        path[i][j]=4;
                    }
                    else
                    {
                        dp[i][j]=dp[i][j-1];
                        path[i][j]=8;
                    }
                }
        fir=false;
        Traversal(n1-1,n2-1);
        cout<<endl;
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: