POJ 1423 Greatest Common Increasing Subsequence【裸LCIS】

时间:2023-03-09 14:26:56
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");
}
}