CodeForces - 10D Digital Root【dp】

【题目描述】
This problem differs from one which was on the online contest.

The sequence a1, a2, …, an is called increasing, if ai < ai + 1 for i < n.

The sequence s1, s2, …, sk is called the subsequence of the sequence a1, a2, …, an, if there exist such a set of indexes 1 ≤ i1 < i2 < … < ik ≤ n that aij = sj. In other words, the sequence s can be derived from the sequence a by crossing out some elements.

You are given two sequences of integer numbers. You are to find their longest common increasing subsequence, i.e. an increasing sequence of maximum length that is the subsequence of both sequences.

【输入】
The first line contains an integer n (1 ≤ n ≤ 500) — the length of the first sequence. The second line contains n space-separated integers from the range [0, 109] — elements of the first sequence. The third line contains an integer m (1 ≤ m ≤ 500) — the length of the second sequence. The fourth line contains m space-separated integers from the range [0, 109] — elements of the second sequence.

【输出】
In the first line output k — the length of the longest common increasing subsequence. In the second line output the subsequence itself. Separate the elements with a space. If there are several solutions, output any.

【样例输入1】
7
2 3 1 6 5 4 6
4
1 3 5 6

【样例输出1】
3
3 5 6

【样例输入2】
5
1 2 0 2 1
3
1 0 1

【样例输出2】
2
0 1

题目链接:https://codeforces.com/contest/10/problem/D

代码如下:

#include 
#include 
#include 
using namespace std;
static const int MAXN=500+10;
int a[MAXN],b[MAXN];
int dp[MAXN][MAXN];
int pre[MAXN][MAXN];
int n,m;
int main()
{
     
	cin>>n;
    for(int i=1;i<=n;i++) cin>>a[i];
    cin>>m;
    for(int i=1;i<=m;i++) cin>>b[i];
    memset(pre,-1,sizeof(pre));
    for(int i=1;i<=n;i++)
    {
     
        int _max=0,k=0;
        for(int j=1;j<=m;j++)
        {
     
            dp[i][j]=dp[i-1][j];
            if(a[i]>b[j] && _max<dp[i-1][j])
            {
     
                _max=dp[i-1][j];
                k=j;
            }
            else if(a[i]==b[j])
            {
     
                dp[i][j]=_max+1;
                pre[i][j]=k;
            }
        }
    }
    int t=1;
    for(int i=2;i<=m;i++)
        if(dp[n][i]>dp[n][t]) t=i;
    cout<<dp[n][t]<<endl;
    if(dp[n][t])
    {
     
        stack<int> ans;
        for(int i=n;i>=1;i--)
            if(pre[i][t]!=-1)
            {
     
                ans.push(a[i]);
                t=pre[i][t];
            }
        while(!ans.empty())
        {
     
            cout<<ans.top()<<" ";
            ans.pop();
        }
    }
    return 0;
 }

你可能感兴趣的:(codeforces,dp)