HDU 1423 Greatest Common Increasing Subsequence(动态规划+最长公共上升子序列)

    xiaoxiao2025-08-30  39

    Problem Description This is a problem from ZOJ 2432.To make it easyer,you just need output the length of the subsequence.   Input Each sequence is described with M - its length (1 <= M <= 500) and M integer numbers Ai (-2^31 <= Ai < 2^31) - the sequence itself.   Output output print L - the length of the greatest common increasing subsequence of both sequences.   Sample Input 1 5 1 4 2 5 -12 4 -12 1 2 4   Sample Output 2

    #include <iostream> #include <cstdio> #include <algorithm> using namespace std; const int N=510; int a[N]; int b[N]; int f[N][N]; int find(int i,int j){ int temp=0; for(int k1=1;k1<i;k1++){ for(int k2=1;k2<j;k2++){ if(a[k1]<a[i]){//! if(f[k1][k2]>temp) temp=f[k1][k2]; } } } return temp; } int main(){ int t; scanf("%d",&t); while(t--){ int ma,mb; int maxn=0; scanf("%d",&ma); for(int i=1;i<=ma;i++) scanf("%d",&a[i]); scanf("%d",&mb); for(int i=1;i<=mb;i++) scanf("%d",&b[i]); for(int i=1;i<=ma;i++){ for(int j=1;j<=mb;j++){ if(a[i]==b[j]) { f[i][j]=find(i,j)+1; } else{ f[i][j]=max(find(i-1,j),find(i,j-1)); } if(f[i][j]>maxn) maxn=f[i][j];//? } } printf("%d\n",maxn); if(t>0) printf("\n");//...? } }

    题意即寻找两个序列的最长公共上升子序列;

    考虑最长公共子序列:定义f[i][j]为a序列第i个位置,b序列第j个位置时最长公共子序列;对于某个状态的f[i][j],如果a[i]=b[j],则f[i][j]为上个状态的最长公共子序列加上1,即f[i-1][j-1]+1;否则f[i][j]就为f[i-1][j]状态的最长公共子序列或f[i][j-1]状态的最长公共子序列,取它们最大值即可;

    对于最长公共上升子序列,我们只需要在最长公共子序列中找出上升的即可,find函数即寻找严格上升的序列;同时因为严格上升,我们需要定义maxn值记录出现的最长公共上升子序列;譬如序列2 3和3 2,如果不记录最大值,直接输出f[2][2]的话,结果会为0(因为循环是严格上升,一旦没有一个严格上升序列就会变成0);

    注意输出格式;

    转载请注明原文地址: https://ju.6miu.com/read-1302142.html
    最新回复(0)