Cod sursa(job #2617357)

Utilizator rebecca0312Andrei Rebecca rebecca0312 Data 21 mai 2020 15:37:56
Problema Seif Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.77 kb
#include <bits/stdc++.h>
using namespace std;

const int NMAX=1005;

int dp[NMAX][NMAX],nxt[2][NMAX],poz[2][26];
char a[2][NMAX];

void citire(int l, int &n) {
    char ch;
    scanf("%c", &ch);
    while(ch!='\n') {
        a[l][n++]=ch;
        scanf("%c", &ch);
    }
    for(int i=0;i<26;i++)
        poz[l][i]=n;
    for(int i=n-1;i>=0;i--) {
        nxt[l][i]=poz[l][a[l][i]-'A'];
        poz[l][a[l][i]-'A']=i;
    }
}

void initializare(int n, int m){
    for(int i=0;i<=n;i++)
        dp[i][m]=0;
    for(int i=0;i<=m;i++)
        dp[n][i]=0;
    for(int i=n-1;i>=0;i--)
        for(int j=m-1;j>=0;j--)
            if(a[0][i]==a[1][j])
                dp[i][j]=1+dp[i+1][j+1];
            else
                dp[i][j]=max(dp[i+1][j], dp[i][j+1]);
}

int main(){
    freopen("seif.in","r",stdin);
    freopen("seif.out","w",stdout);
    int t;
    scanf("%d", &t);
    for(int p=1;p<=t;p++){
        int k,n=0,m=0;
        scanf("%d ", &k);
        citire(0, n);
        citire(1, m);
        initializare(n, m);
        int x=0,y=0;
        bool ok=1;
        while(ok){
            ok=0;
            int ch='Z'-'A';
            while(!ok && ch>=0) {
                while(poz[0][ch]<x)
                    poz[0][ch]=nxt[0][poz[0][ch]];
                while(poz[1][ch]<y)
                    poz[1][ch]=nxt[1][poz[1][ch]];
                if(poz[0][ch]<n && poz[1][ch]<m && dp[poz[0][ch]][poz[1][ch]]>=k) {
                    ok=1;
                    printf("%c", ch+'A');
                    k--;
                    x=poz[0][ch]+1;
                    y=poz[1][ch]+1;
                }
                ch--;
            }
            if(x>=n || y>=m)
                ok=0;
        }
        printf("\n");
    }
    return 0;
}