Cod sursa(job #2099571)

Utilizator dahaandreiDaha Andrei Codrin dahaandrei Data 4 ianuarie 2018 15:10:21
Problema Cel mai lung subsir comun Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.01 kb
#include <fstream>
#include <stack>

using namespace std;

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

int mat[1025][1025];
int v1[1025], v2[1025];
stack <int>answer;

int main(){
  int n, m;
  in >> n >> m;

  for (int i = 1; i <= n; ++ i)
    in >> v1[i];
  for (int i = 1; i <= m; ++ i)
    in >> v2[i];

  for (int i = 1; i <= n; ++ i){
    for (int j = 1; j <= m; ++ j){
      if (v1[i] == v2[j])
        mat[i][j] = mat[i - 1][j - 1] + 1;
      else
        mat[i][j] = max(mat[i - 1][j], mat[i][j - 1]);
    }
  }

  int l = mat[n][m];
  int cnt = 1;
  int lasti = 0, lastj = 0;

  out << l << '\n';

  int i = n;
  int j = m;

  while (cnt <= l && i > 0 && j > 0){
    if (v1[i] == v2[j]){
      answer.push(v1[i]);
      i --;
      j --;
      cnt ++;
    }
    else{
      if (mat[i][j] == mat[i - 1][j])
        i --;
      else
        j --;
    }
  }

  while (answer.size()){
    out << answer.top() << " ";
    answer.pop();
  }

  return 0;
}