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("%dn",ans);
if(ans)
{
fir=0;
su(ed.first,ed.second);printf("n");
}
}
return 0;
}
最后
以上就是现代发夹最近收集整理的关于POJ 2127 Greatest Common Increasing Subsequence的全部内容,更多相关POJ内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复