Cod sursa(job #3364426)

Utilizator Alexandru_OrzeaOrzea Alexandru Alexandru_Orzea Data 3 septembrie 2026 11:24:27
Problema Cel mai lung subsir comun Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
/******************************************************************************

                              Online C++ Compiler.
               Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.

*******************************************************************************/

#include <fstream>

using namespace std;

ifstream f("cmlsc.in");
ofstream g("cmlsc.out");

int m, n, l, a[1025], b[1025], dp[1025][1025], s[1025], poz;

int main()
{
    f>>m>>n;
    
    for(int i=1; i<=m; i++)
    f>>a[i];
    
    for(int i=1; i<=n; i++)
    f>>b[i];
    
    for(int i=1; i<=m; i++){
        for(int j=1; j<=n; j++){
            
            if(a[i] == b[j])
            dp[i][j] = dp[i-1][j-1] +1;
            
            else
            dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
        }
    }
    g<<dp[m][n]<<'\n';
    
    int i=m, j=n;
    
    while(i>0 && j>0){
        if(a[i] == b[j]){
            s[poz++] = a[i];
            i--;
            j--;
        }
        
        else if(dp[i-1][j] > dp[i][j-1])
                i--;
                
            else
            j--;
        }
    
    for(int i=poz-1; i>=0; i--)
    g<<s[i]<<' ';

    return 0;
}