动态规划LCIS

来源:互联网 发布:pcb 合拼算法 编辑:程序博客网 时间:2024/06/05 15:26

2000:最长公共子上升序列

总Time Limit:
10000ms
Memory Limit:
65536kB

Description
给定两个整数序列,写一个程序求它们的最长上升公共子序列。
当以下条件满足的时候,我们将长度为N的序列S1 , S2 , … , SN 称为长度为M的序列A1 , A2 , … , AM 的上升子序列:

存在 1 <= i1 < i2 < . . . < iN <= M ,使得对所有 1 <= j <=N,均有Sj = Aij,且对于所有的1 <= j < N,均有Sj < Sj+1。

Input
每个序列用两行表示,第一行是长度M(1 <= M <= 500),第二行是该序列的M个整数Ai (-231 <= Ai < 231 )
Output
在第一行,输出两个序列的最长上升公共子序列的长度L。在第二行,输出该子序列。如果有不止一个符合条件的子序列,则输出任何一个即可。
Sample Input

51 4 2 5 -124-12 1 2 4

Sample Output

21 4
#include<iostream>  #include<vector>  #define MAX(a,b) (a>b?a:b)using namespace std;struct Node {    int val = 0;    vector<int>v;    bool operator > (const Node &a) { return val > a.val; }};int main() {    int a[501], b[501];    int t;    cin >> t;    while (t--)    {        Node dp[501];        int m, n;        cin >> m;        for (int i = 1; i <= m; i++)            cin >> a[i];        cin >> n;        for (int i = 1; i <= n; i++)            cin >> b[i];        for (int i = 1; i <= n; i++)        {            Node Max;            for (int j = 1; j <= m; j++) {                if (b[i] > a[j])                    Max = MAX(Max,dp[j]);                if (b[i] == a[j]) {                    dp[j] = Max;                    dp[j].val += 1;                    dp[j].v.push_back(b[i]);                }            }        }        Node Max = dp[1];        for (int i = 2; i <= m; i++) {            Max = MAX(dp[i], Max);        }        cout << Max.val << endl;        for (auto i : Max.v)            cout << i << " ";        cout << endl;    }    return 0;}