POJ 1423 Greatest Common Increasing Subsequence【裸LCIS】

連接:



Greatest Common Increasing Subsequence

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 2757    Accepted Submission(s): 855


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
 

Source
 

Recommend
lcy



算法:

 

LCIS 【最長公共上升子序列分析


code:

注意格式 問題:

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
using namespace std;


const int maxn = 500+50;
int dp[maxn][maxn];
int a[maxn],b[maxn];
int m,n;


/****
求序列 A 長度爲 N 和序列 B 長度爲 M 的 LCS
序列下標從 1 開始
*/
int LCS()
{
    for(int i = 1; i <= n; i++)
    {
        int tmp = 0; //記錄在i肯定,且a[i]>b[j]的時候dp[i,j]的最大值
        for(int j = 1; j <= m; j++)
        {
            dp[i][j] = dp[i-1][j];
            if(a[i] > b[j])
            {
                tmp = dp[i-1][j];
            }
            else if(a[i] == b[j])
                dp[i][j] = tmp+1;
        }
    }
//for(int i = 1; i <= m; i++) printf("%d ", dp[n][i]); printf("\n");


    int ans = 0;
    for(int i = 1; i <= m; i++)
        ans = max(ans, dp[n][i]);
    return ans;


}


int main()
{
    int T;
    scanf("%d", &T);
    while(T--)
    {
        memset(dp,0,sizeof(dp));


        scanf("%d", &n);
        for(int i = 1; i <= n; i++)
            scanf("%d", &a[i]);
        scanf("%d", &m);
        for(int j = 1; j <= m; j++)
            scanf("%d", &b[j]);


        printf("%d\n",LCS());
        if(T != 0) printf("\n");
    }
}





內存優化:

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
using namespace std;

const int maxn = 500+50;
int dp[maxn];
int a[maxn],b[maxn];
int m,n;

/****
求序列 A 長度爲 N 和序列 B 長度爲 M 的 LCS
序列下標從 1 開始
*/
int LCS()
{
    for(int i = 1; i <= n; i++)
    {
        int tmp = 0;
        for(int j = 1; j <= m; j++)
        {
            if(a[i] > b[j] && dp[j] > tmp)
            {
                tmp = dp[j];
            }
            else if(a[i] == b[j])
                dp[j] = tmp+1;
        }
    }

    int ans = 0;
    for(int i = 1; i <= m; i++)
        ans = max(ans, dp[i]);
    return ans;
}

int main()
{
    int T;
    scanf("%d", &T);
    while(T--)
    {
        memset(dp,0,sizeof(dp));

        scanf("%d", &n);
        for(int i = 1; i <= n; i++)
            scanf("%d", &a[i]);
        scanf("%d", &m);
        for(int j = 1; j <= m; j++)
            scanf("%d", &b[j]);

        printf("%d\n",LCS());
        if(T != 0) printf("\n");
    }
}
相關文章
相關標籤/搜索