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<string.h>
#include<stdio.h>
#include<math.h>
using namespace std;
int a[550],f[550][550],b[550];
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]&&b[k2]<b[j])
{
if(f[k1][k2]>temp) temp=f[k1][k2];
}
}
}
return temp;
}
int main()
{
int T;
cin>>T;
for(int t=1; t<=T; t++)
{
int n,m,maximum=-1;
memset(f,0,sizeof(f));
scanf("%d",&n);
for(int i=1; i<=n; i++)
{
scanf("%d",&a[i]);
}
scanf("%d",&m);
for(int i=1; i<=m; i++)
{
scanf("%d",&b[i]);
}
for(int i=1; i<=n; i++)
{
for(int j=1; j<=m; 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]>maximum) maximum=f[i][j];
}
}
cout<<maximum<<endl;
if(t!=T) cout<<endl;
}
return 0;
}
本文介绍了解决ZOJ2432问题的方法,该问题是求两个序列的最大公共递增子序列。通过动态规划算法,结合最长公共子序列与最长递增子序列的概念,有效地解决了这一问题。
404

被折叠的 条评论
为什么被折叠?



