您的位置:首页 > 产品设计 > UI/UE

poj2127 Greatest Common Increasing Subsequence

2016-07-26 21:00 483 查看
Description You are given two sequences of integer numbers. Write a

program to determine their common increasing subsequence of maximal

possible length. Sequence S1 , S2 , … , SN of length N is called

an increasing subsequence of a sequence A1 , A2 , … , AM of length

M if there exist 1 <= i1 < i2 < … < iN <= M such that Sj = Aij for

all 1 <= j <= N , and Sj < Sj+1 for all 1 <= j < N .

Input Each sequence is described with M — its length (1 <= M <= 500)

and M integer numbers Ai (-231 <= Ai < 231 ) — 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.

动态规划。

dp[i][j]表示考虑了a[]的前i位,考虑了b[]的前j位,且b[]的第j位一定包含的最大长度。

dp[i][j]=dp[i-1][j] (a[i]!=b[j])

dp[i][j]=max{dp[i-1][k]+1} (a[i]=b[j]>b[k])

很容易写出N(n^3)算法。

考虑到k的范围1<=k< j且每一次循环时外层的i不发生变化,可以在j的循环时维护一个最大的dp[i-1][k]使得a[i]>b[k],每次用当前的j更新,直接取即为答案。实现O(1)转移,总复杂度O(n^2)。

#include<cstdio>
#include<cstring>
int dp[510][510],pre[510][510],a[510],b[510],sta[510];
int main()
{
int i,j,k,m,n,p,q,x,y,z,ans=0,top=0;
while (scanf("%d",&m)==1)
{
memset(dp,0,sizeof(dp));
memset(pre,0,sizeof(pre));
ans=top=0;
for (i=1;i<=m;i++)
scanf("%d",&a[i]);
scanf("%d",&n);
for (i=1;i<=n;i++)
scanf("%d",&b[i]);
for (i=1;i<=m;i++)
{
x=0;
for (j=1;j<=n;j++)
{
if (a[i]==b[j])
{
dp[i][j]=dp[i-1][x]+1;
if (dp[i][j]>ans)
{
ans=dp[i][j];
p=j;
}
pre[i][j]=x;
}
else dp[i][j]=dp[i-1][j];
if (a[i]>b[j]&&dp[i-1][j]>dp[i-1][x]) x=j;
}
}
printf("%d\n",ans);
if (!ans)
continue;
for (i=m;top<ans;i--)
if (a[i]==b[p])
{
sta[++top]=b[p];
p=pre[i][p];
}
while (top>1)
printf("%d ",sta[top--]);
printf("%d\n",sta[1]);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  动态规划