UVA 531 LCS + 输出

题意:

求最长公共子序列并输出序列。

解题:

处理一下输入,把单词存起来比较, 然后递归输出路径~

#include <bits/stdc++.h>
#define ll long long
using namespace std;

const int maxn = 110;
const int INF = 0x3f3f3f3f;

string  a[maxn], b[maxn];
int d[maxn][maxn], p[maxn][maxn], f = 0;
void print(int x, int y)
{
    if(!x || !y) return ;
    if(p[x][y] == 1) {
        print (x-1, y-1);
        if(f) printf(" ");
        else f = 1;
        cout << a[x];
    }
    else if(p[x][y] == 0) print (x-1, y);
    else print (x, y-1);
}
int main()
{
   // freopen("in.txt","r",stdin);
  // freopen("out.txt","w",stdout);
    while (cin >> a[1]) {
        int cnt = 2, cnt2 = 1;
        while (cin >> a[cnt] && a[cnt][0] != '#') cnt ++;
        while (cin >> b[cnt2] && b[cnt2][0] != '#') cnt2 ++;
        memset (d,0,sizeof(d));
        memset (p,0,sizeof(p));
        for (int i = 1; i < cnt; i ++) {
            for (int j = 1; j < cnt2; j ++) {
                if(a[i] == b[j]) {
                    d[i][j] = d[i-1][j-1] + 1;
                    p[i][j] = 1;
                }
                else if (d[i-1][j] >= d[i][j-1]) {
                    d[i][j] = d[i-1][j];
                    p[i][j] = 0;
                }
                else {
                    d[i][j] = d[i][j-1];
                    p[i][j] = -1;
                }
            }
        }
        f = 0;
        print (cnt-1, cnt2-1);
        printf ("\n");
    }
    return 0;
}

 

posted @ 2016-08-17 21:00  Ember  阅读(213)  评论(0编辑  收藏  举报