Cod sursa(job #1516225)

Utilizator felixiPuscasu Felix felixi Data 2 noiembrie 2015 21:01:37
Problema Seif Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.6 kb
#include <fstream>
#include <string>

using namespace std;

const int N = 1005;
const int alphabetSize = 26;

int d[N][N], nextA[alphabetSize][N], nextB[alphabetSize][N];
int n, m, k;

string a;
string b;

ifstream cin("seif.in");
ofstream cout("seif.out");

void solve() {
    for(int i = 1; i <= n + 1; ++i)
    {
        for(int j = 1; j <= m + 1; ++j)
        {
            d[i][j] = 0;
        }
    }
    for(int j = 0; j < alphabetSize; ++j)
    {
        for(int i = 0; i <= n + 1; ++i)
        {
            nextA[j][i] = 0;
        }
    }
    for(int j = 0; j < alphabetSize; ++j)
    {
        for(int i = 0; i <= m + 1; ++i)
        {
            nextB[j][i] = 0;
        }
    }

    for(int i = n; i >= 1; --i)
    {
        for(int j = m; j >= 1; --j)
        {

            d[i][j] = d[i][j + 1];

            if(a[i] == b[j] && d[i][j] < d[i + 1][j + 1] + 1)
            {
                d[i][j] = d[i + 1][j + 1] + 1;
            }

            if(d[i + 1][j] > d[i][j])
            {
                d[i][j] = d[i + 1][j];
            }
        }
    }

    for(int j = 0; j < alphabetSize; ++j)
    {
        for(int i = n; i >= 0; --i)
        {
            if(a[i + 1] - 'A' == j)
            {
                nextA[j][i] = i + 1;
            }
            else
            nextA[j][i] = nextA[j][i + 1];
        }
    }

    for(int j = 0; j < alphabetSize; ++j)
    {
        for(int i = m; i >= 0; --i)
        {
            if(b[i + 1] - 'A' == j)
            {
                nextB[j][i] = i + 1;
            }
            else
            nextB[j][i] = nextB[j][i + 1];
        }
    }

    int i = 0, j = 0;
    while(true)
    {
        int passed = 0;
        for(int l = alphabetSize; l >= 0; --l)
        {
            if( d[ nextA[l][i] ][ nextB[l][j] ] >= k && d[ nextA[l][i] ][ nextB[l][j] ] ) {
                cout << (char) ('A' + l);
                i = nextA[l][i];
                j = nextB[l][j];
                passed = 1;
                --k;
                break;
            }
        }
        if(!passed) {
            break;
        }
    }
    cout << '\n';
}
int main() {
    int t;
    cin >> t;
    for(;t;--t) {
        cin >> k;
        cin >> a >> b;
        n = a.size();
        m = b.size();
        a.resize(a.size() + 1);
        b.resize(b.size() + 1);
        for(int i = n; i > 0; --i)
        {
            a[i] = a[i - 1];
        }

        for(int i = m; i > 0; --i)
        {
            b[i] = b[i - 1];
        }

        solve();
    }

    return 0;
}