Description
You are given two sequences of integer numbers. Write a program to determine their common increasing subsequence of maximal possible length.
Sequence S 1 , S 2 , . . . , S N of length N is called an increasing subsequence of a sequence A 1 , A 2 , . . . , A M of length M if there exist 1 <= i 1 < i 2 < . . . < i N <= M such that S j = A ij for all 1 <= j <= N , and S j < S j+1 for all 1 <= j < N .
Sequence S 1 , S 2 , . . . , S N of length N is called an increasing subsequence of a sequence A 1 , A 2 , . . . , A M of length M if there exist 1 <= i 1 < i 2 < . . . < i N <= M such that S j = A ij for all 1 <= j <= N , and S j < S j+1 for all 1 <= j < N .
Input
Each sequence is described with M --- its length (1 <= M <= 500) and M integer numbers A
i (-2
31 <= A
i < 2
31 ) --- the sequence itself.
Output
On the first line of the output file 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.
Sample Input
5 1 4 2 5 -12 4 -12 1 2 4
Sample Output
2 1 4
Source
Northeastern Europe 2003, Northern Subregion
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
求最长上升公共子序列~
在草稿箱中积了很长时间的坑,今天做的时候才发现就是前几天我不会的那道考试题嘛……悲伤……
#include<cstdio>
#include<cstring>
#include<iostream>
using namespace std;
int dp[505][505],opt[505],from[505],a[505],b[505],s1,s2,ans,maxn;
pair<int,int> pre[505][505];
bool fir;
void su(int u,int v)
{
if(!u && !v) return;
su(pre[u][v].first,pre[u][v].second);
if(!fir)
{
fir=1;printf("%d",a[u]);return;
}
printf(" %d",a[u]);
}
int main()
{
while(scanf("%d",&s1)!=EOF)
{
memset(dp,0,sizeof(dp));
memset(opt,0,sizeof(opt));
ans=0;pair<int,int> ed;
for(int i=1;i<=s1;i++) scanf("%d",&a[i]);scanf("%d",&s2);
for(int j=1;j<=s2;j++) scanf("%d",&b[j]);
for(int i=1;i<=s1;i++)
{
maxn=0;
for(int j=1;j<=s2;j++)
{
if(a[i]>b[j] && opt[maxn]<opt[j]) maxn=j;
if(b[j]==a[i])
{
dp[i][j]=opt[maxn]+1;
pre[i][j].first=from[maxn];
pre[i][j].second=maxn;
if(ans<dp[i][j])
{
ans=dp[i][j];
ed.first=i;
ed.second=j;
}
}
if(opt[j]<dp[i][j])
{
opt[j]=dp[i][j];
from[j]=i;
}
}
}
printf("%d\n",ans);
if(ans)
{
fir=0;
su(ed.first,ed.second);printf("\n");
}
}
return 0;
}

本文介绍了一种解决最长上升公共子序列问题的算法实现,通过动态规划方法找到两个整数序列之间的最长上升公共子序列,并附带示例输入输出。
1355

被折叠的 条评论
为什么被折叠?



