您的位置:首页 > 其它

(LCIS)最长公共上升子序列 ZOJ 2432

2014-04-26 22:38 399 查看
Greatest Common Increasing Subsequence
 

 

Time Limit: 2 Seconds      Memory Limit: 65536 KB      Special Judge
 

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. 

Input

Each sequence is described with M - its length (1 <= M <= 500) and M integer numbers Ai (-2^31 <= Ai < 2^31) - the sequence itself.

Output

On the first line of the output 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.

This problem contains multiple test cases!

The first line of a multiple input is an integer N, then a blank line followed by N input blocks. Each input block is in the format indicated in the problem description. There is a blank line between input blocks.

The output format consists of N output blocks. There is a blank line between output blocks.



Sample Input


1

5

1 4 2 5 -12

4

-12 1 2 4

Sample Output

2

1 4

 

题意:给出两串数字,要你输出他们的最长公共上升子序列。并且要输出这个序列是什么。

 

思路:具体的可以看http://wenku.baidu.com/link?url=5c_6_9rR4pAJ0u2P5AKfMLw5Z1aKoZrNcMLQ56DZ7SuZAlD-nBzMCzzoGDzwuSf194SSopoEFBzFAni5clemvpWxCr2NuBOo-DsqC_JBIDi

 

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<string.h>
using namespace std;
const int maxn = 1000 + 5;
#define LL long long
int n, m;
LL a[maxn], b[maxn];
int f[maxn][maxn];
int pre[maxn][maxn];

int main()
{
int T; cin >> T;
while (T--) {
scanf("%d", &n);
for (int i = 1; i <= n; ++i) scanf("%lld", a + i);
scanf("%d", &m);
for (int i = 1; i <= m; ++i) scanf("%lld", b + i);
memset(pre, -1, sizeof(pre));
memset(f, 0, sizeof(f));
for (int i = 1; i <= n; ++i) {
int v = 0, k = 0;
for (int j = 1; j <= m; ++j) {
//		pre[i][j] = pre[i - 1][j];
f[i][j] = f[i - 1][j];
if (a[i] > b[j] && v < f[i - 1][j]) v = f[i - 1][j], k = j;
if (a[i] == b[j] && v + 1>f[i][j]) f[i][j] = v + 1, pre[i][j] = k;
}
}
int k = 1;
for (int i = 1; i <= m; ++i)
if (f
[i]>f
[k]) k = i;
printf("%d\n", f
[k]);
if (f
[k] == 0) continue;
int i = n;
vector<int> ans;
for (int i = n; i >= 1;--i)
if (pre[i][k] != -1) ans.push_back(a[i]), k = pre[i][k];
printf("%d", ans.back());
for (int i = ans.size() - 2; i >= 0; --i) printf(" %d", ans[i]);
printf("\n");
}
}


 

 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: