Cod sursa(job #2795302)

Utilizator Robert.BrindeaBrindea Robert Robert.Brindea Data 6 noiembrie 2021 10:58:23
Problema Cel mai lung subsir comun Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.93 kb
#include <iostream>
#include <fstream>
#include <stack>
#define MAXN 1030

using namespace std;

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

int n, m, a[MAXN], b[MAXN], mat[MAXN][MAXN];
stack<int> sol;
int main()
{
    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]) mat[i][j] = mat[i-1][j-1]+1;
            else mat[i][j] = max(mat[i-1][j], mat[i][j-1]);
    int k = mat[n][m], j = m;
    fout << k << "\n";
    for(int i = n, j = m; i > 0 && j > 0;)
    {
        if(a[i] == b[j])
        {
            sol.push(a[i]);
            i--;
            j--;
        }
        else
        {
            if(mat[i-1][j] > mat[i][j-1]) i--;
            else j--;
        }
    }
    while(!sol.empty()) fout << sol.top() << " ", sol.pop();
    return 0;
}