This is the classic LCS problem. Since it requires you-to-print one longest common subsequence, just use the O (m*n)-space version here.
My accepted code is as follows.
1#include <iostream>2#include <vector>3#include <algorithm>4 5 using namespacestd;6 7vector<int> LCS (vector<int>& A, vector<int>&b) {8 intn = a.size (), M =b.size ();9vector<vector<int> > DP (n +1, vector<int> (M +1,0));Ten for(inti =1; I <= N; i++) { One for(intj =1; J <= M; J + +) { A if(A[i-1] = = B[j-1]) Dp[i][j] = dp[i-1][j-1] +1; - ElseDP[I][J] = max (Dp[i][j-1], Dp[i-1][j]); - } the } -vector<int>Res; - for(inti = n, j = m; I >=1&& J >=1;) { - if(A[i-1] = = B[j-1]) { +Res.push_back (A[i-1]); -i--; +j--; A } at Else if(Dp[i-1][J] >= dp[i][j-1]) i--; - Elsej--; - } - Reverse (Res.begin (), Res.end ()); - returnRes; - } in - intMain () { to /*Enter your code here. Read input from STDIN. Print output to STDOUT*/ + intN, M; - while(SCANF ("%d%d", &n, &m)! =EOF) { thevector<int>a (n); *vector<int>B (m); $ for(inti =0; I < n; i++)Panax Notoginsengscanf"%d", &a[i]); - for(inti =0; I < m; i++) thescanf"%d", &b[i]); +vector<int> res =LCS (A, b); A for(inti =0; I < (int) Res.size (); i++) theprintf"%d", Res[i]); +printf"\ n"); - } $ return 0; $}
Well, try this problem here and get Accepted:)
[Hackerrank] The longest Common subsequence