POJ 2250 - Compromise ( 最长公共子序列的DFS输出 )

题意

(多组输入)给出两段文字, 输出最长公共子序列

思路

DFS回溯输出最长公共子序列

AC代码

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <set>
#include <map>
#include <vector>
using namespace std;
map<int, string> id;
map<int, string>::iterator it;
set<string> st;
const int maxn = 105;
int dp[maxn][maxn];
short int mrk[maxn][maxn];  //用于标记回溯
vector<int> s1, s2;
int len1, len2;
bool space = 0;

int getid(string a)
{
    it = id.begin();
    for(;it!=id.end();it++)
        if( it->second == a )
            return it->first;
}

void LCS()  //最长公共子序列
{
    memset(dp, 0, sizeof dp);
    for(int i = 1; i <= len1; i++)
        mrk[i][0] = 1;
    for(int i = 1; i <= len2; i++)
        mrk[0][i] = -1;
    for(int i = 1; i <= len1; i++){
        for(int j = 1; j <= len2; j++){
            if( s1[i-1] == s2[j-1] )
            {
                dp[i][j] = dp[i-1][j-1]+1;
                mrk[i][j] = 0;
            }
            else if( dp[i-1][j] > dp[i][j-1] )
            {
                dp[i][j] = dp[i-1][j] ;
                mrk[i][j] = 1;
            }
            else
            {
                dp[i][j] = dp[i][j-1] ;
                mrk[i][j] = -1;
            }
        }
    }
}

void putLCS(int x, int y)
{
    if( !x && !y ) return;
    if( mrk[x][y] == 0 )
    {
        putLCS(x-1, y-1);
        if(space) cout << " ";
        cout << id[s1[x-1]];
        space = 1;
    }
    else if( mrk[x][y] == 1 )
    {
        putLCS(x-1, y);
    }
    else
    {
        putLCS(x, y-1);
    }
}

int main()
{
    string a;
    int flag = 1;
    int cnt = 0;
    while( cin >> a )
    {
        if( a == "#" )
        {
            if( flag == 1 )
            {
                flag = 0;
            }
            else
            {
                len1 = (int)s1.size();
                len2 = (int)s2.size();
                LCS();
                putLCS(len1, len2);
                cout << "\n";
                flag = 1;
                cnt = 0;
                space = 0;
                if(st.size())  st.clear();
                if(id.size())  id.clear();
                if(s1.size())  s1.clear();
                if(s2.size())  s2.clear();
            }
            continue;
        }
        if( flag )
        {
            if( !st.count(a) )
            {
                st.insert(a);
                id[cnt] = a;
                s1.push_back(cnt);
                cnt++;
            }
            else s1.push_back( getid(a) );
        }
        else
        {
            if( !st.count(a) )
            {
                st.insert(a);
                id[cnt] = a;
                s2.push_back(cnt);
                cnt++;
            }
            else s2.push_back( getid(a) );
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/JinxiSui/article/details/81203238