Cod sursa(job #2572517)

Utilizator mjmilan11Mujdar Milan mjmilan11 Data 5 martie 2020 13:10:27
Problema Cel mai lung subsir comun Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("cmlsc.in");
ofstream fout("cmlsc.out");

const int NMAX = 1025;
int a[NMAX],b[NMAX],rasp[NMAX];
int dp[NMAX][NMAX];
pair<int,int> prev[NMAX][NMAX];

int main()
{
    int n,m;
    fin >> n >> m;
    for(int i=1;i<=n;i++) fin >> a[i];
    for(int i=1;i<=m;i++) fin >> b[i];
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            if(a[i]==b[j]){
                dp[i][j]=dp[i-1][j-1]+1;
                prev[i][j]=make_pair(i-1,j-1);
            }
            else{
                dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
                if(dp[i-1][j]<dp[i][j-1])
                      prev[i][j]=make_pair(i,j-1);
                else  prev[i][j]=make_pair(i-1,j);
            }
        }
    }
    fout << dp[n][m] << '\n';
    bool ok=false;
    int x=n,y=m,k=0;
    while(ok==false){
        if(prev[x][y].first==x-1 and prev[x][y].second==y-1){
            rasp[++k]=a[x];
        }
        x=prev[x][y].first;
        y=prev[x][y].second;
        if(x==0 and y==0) ok=true;
    }
    for(int i=k;i>=1;i--) fout << rasp[i] << ' ';
    return 0;
}