Cod sursa(job #3002908)

Utilizator domistnSatnoianu Dominic Ioan domistn Data 15 martie 2023 12:26:10
Problema Cel mai lung subsir comun Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.82 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 1024;

int a[NMAX + 1], b[NMAX + 1], n, m,
    dp[NMAX + 1][NMAX + 1];

int main()
{
    freopen("cmlsc.in", "r", stdin);
    freopen("cmlsc.out", "w", stdout);
    scanf("%d%d", &n, &m);
    for(int i = 1; i <= n; ++i) scanf("%d", &a[i]);
    for(int i = 1; i <= m; ++i) scanf("%d", &b[i]);
    for(int i = 1; i <= n; ++i)
        for(int j = 1; j <= m; ++j) {
            dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) +
                       (a[i] == b[j]);
        }
    printf("%d\n", dp[n][m]);
    stack<int> st;
    int x = n, y = m;
    while(x && y) {
        if(a[x] == b[y]) st.push(a[x]);
        if(dp[x - 1][y] > dp[x][y - 1]) x--;
        else y--;
    }
    while(!st.empty()) printf("%d ", st.top()), st.pop();
    return 0;
}