当前位置: 代码迷 >> 综合 >> CF10D LCIS 最长公共上升子序列
  详细解决方案

CF10D LCIS 最长公共上升子序列

热度:46   发布时间:2024-01-15 07:45:05.0

题意翻译

求两个串的最长公共上升子序列。

题目描述

This problem differs from one which was on the online contest.

The sequence a_{1},a_{2},...,a_{n}a1?,a2?,...,anis called increasing, if a_{i}<a_{i+1}ai?<ai+1for i<ni<n .

The sequence s_{1},s_{2},...,s_{k}s1?,s2?,...,skis called the subsequence of the sequence a_{1},a_{2},...,a_{n}a1?,a2?,...,an, if there exist such a set of indexes 1<=i_{1}<i_{2}<...<i_{k}<=n1<=i1?<i2?<...<ik?<=n that a_{ij}=s_{j}aij?=sj. In other words, the sequence sscan be derived from the sequence aa 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 nn 1<=n<=5001<=n<=500 ) — the length of the first sequence. The second line contains nn space-separated integers from the range [0,10^{9}][0,109— elements of the first sequence. The third line contains an integer mm 1<=m<=5001<=m<=500 ) — the length of the second sequence. The fourth line contains mm space-separated integers from the range [0,10^{9}][0,109— elements of the second sequence.

输出格式:
 

In the first line output kk — 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 

模板题,解析(点这里)

#include<iostream>
#include<math.h>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<vector>
#include<map>
using namespace std;
typedef long long lld;
const int oo=0x3f3f3f3f;
const lld OO=1LL<<61;
const lld MOD=1000000007;
#define eps 1e-6
#define maxn 505
int dp[maxn][maxn];
int path[maxn][maxn];
int a[maxn],b[maxn];
int n,m;void dfs(int x)
{if(path[n][x]==-1){printf("%d",b[x]);return ;}dfs(path[n][x]);printf(" %d",b[x]);
}int main()
{while(scanf("%d",&n)!=EOF){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(path,-1,sizeof path);for(int i=1;i<=n;i++){int pos=-1,Max=0;for(int j=1;j<=m;j++){dp[i][j]=dp[i-1][j];path[i][j]=path[i-1][j];if(a[i]==b[j]&&dp[i][j]<Max+1){dp[i][j]=Max+1;path[i][j]=pos;}if(a[i]>b[j]&&dp[i-1][j]>Max){Max=dp[i-1][j];pos=j;}}}int ans=1;for(int i=1;i<=m;i++)if(dp[n][ans]<dp[n][i])ans=i;printf("%d\n",dp[n][ans]);if(dp[n][ans])dfs(ans);puts("");}return 0;
}