ZOJ 2432-Greatest Common Increasing Subsequence

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

题目大意就是求公共最长上升自序列,并输出路径。

之前写过怎么求公共上升子序列的长度,关于路径需要用二维数组来记录每一个点的前驱节点。由于还要记录层数,所以加上一个偏移量表示层数就可以了。

#include<bits/stdc++.h>

using namespace std;
const int N = 1007;
int n, m;
int a[N], b[N], dp[N];
int pre[N][N];

void solve()
{
    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(dp, 0, sizeof(dp));
    memset(pre, -1, sizeof(pre));

    for(int i=1; i<=n; ++ i)
    {
        int k = 0, x = 0;
        for(int j=1; j<=m; ++ j)
        {
            if(dp[j])
                pre[i][j] = pre[i-1][j];

            if(a[i] == b[j] && dp[j] <= dp[k])
                dp[j] = dp[k] + 1, pre[i][j] = x * 1000 + k;

            if(dp[j] > dp[k] && b[j] < a[i])
                k = j, x = i;
        }
    }

    int ans = 0;
    for(int i=1; i<=m; ++ i)
    {
        if(dp[i] > dp[ans])
            ans = i;
    }

    printf("%d
", dp[ans]);
    stack<int> stk;
    for(int x = n, k = ans, t; pre[x][k] != -1; t = pre[x][k], x = t / 1000, k = t % 1000)
        stk.push(b[k]);
    while(stk.size())
    {
        printf("%d ", stk.top());
        stk.pop();
    }
    printf("
");
}

int main()
{
    int t;
    scanf("%d", &t);
    for(int i=0; i<t; ++ i)
        solve();
    return 0;
}

写完这份代码感觉自己好傻逼啊,一个简单的错误调了半天bug。

写这部分的时候

for(int x = n, k = ans, t; pre[x][k] != -1; t = pre[x][k], x = t / 1000, k = t % 1000)
        stk.push(b[k]);

之前是写成这样的

for(int x = n, k = ans; pre[x][k] != -1; x = pre[x][k] / 1000, k = pre[x][k] % 1000)
        stk.push(b[k]);

这样的一个错误调了老长时间。。

原文地址:https://www.cnblogs.com/aiterator/p/6806207.html