Greatest Common Increasing Subsequence
Time Limit: 10000MS | Memory Limit: 65536K | |
Total Submissions: 10113 | Accepted: 2663 | |
Case Time Limit: 2000MS | Special Judge |
Description
You are given two sequences of integer numbers. Write a program to determine their common increasing subsequence of maximal possible length.
Sequence S1 , S2 , . . . , SN of length N is called an increasing subsequence of a sequence A1 , A2 , . . . , AM of length M if there exist 1 <= i1 < i2 < . . . < iN <= M such that Sj = Aij for all 1 <= j <= N , and Sj < Sj+1 for all 1 <= j < N .
Sequence S1 , S2 , . . . , SN of length N is called an increasing subsequence of a sequence A1 , A2 , . . . , AM of length M if there exist 1 <= i1 < i2 < . . . < iN <= M such that Sj = Aij for all 1 <= j <= N , and Sj < Sj+1 for all 1 <= j < N .
Input
Each sequence is described with M --- its length (1 <= M <= 500) and M integer numbers Ai (-231 <= Ai < 231 ) --- the sequence itself.
Output
On the first line of the output file print L --- the length of the greatest common increasing subsequence of both sequences. On the second line print the subsequence itself. If there are several possible answers, output any of them.
Sample Input
5 1 4 2 5 -12 4 -12 1 2 4
Sample Output
2 1 4
Source
#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; int f[1010][1010], a[1010], b[1010], n, m, last, id[1010][1010], ly; void print(int i, int j, int pos, int& first) { if (j == 0)return ; print(i-1,id[i][j], j, first); if (j != pos) { if (first) { printf("%d", b[j]); first = 0; } else printf(" %d", b[j]); } } int main() { while (~scanf("%d", &n)) { for (int i = 1; i <= n; i++) scanf("%d", &a[i]); scanf("%d", &m); for (int i = 1; i <= m; i++) scanf("%d", &b[i]); memset(f, 0, sizeof(f)); for (int i = 1; i <= n; i++) { int maxx = 0;ly = 0; for (int j = 1; j <= m; j++) { f[i][j] = f[i-1][j]; id[i][j] = j; if (a[i] > b[j]&&maxx < f[i-1][j]){maxx = f[i-1][j];ly = j;} if (a[i] == b[j]){ f[i][j] = maxx + 1; id[i][j] = ly; } } } int maxx = 0; for (int i = 1; i <= m; i++) if (maxx < f[n][i]){ maxx = f[n][i]; last = i; } printf("%d ", maxx); int first = 1; print(n, last, 0, first); printf(" "); } }