poj2127 Greatest Common Increasing Subsequence

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]);
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值