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
题意:
求最长公共上升子序列的长度。
思路:采用dp思想,f[i][j]表示第一个序列的前i个元素和第二个序列的前j个元素的最长上升公共子序列
状态转移方程:
①f[i][j] =f[i-1][j] (a[i] != b[j])
②f[i][j] = max(f[i-1][k]+1) (1 <= k <= j-1 && b[j] > b[k])
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int f[2000][2000];
int main()
{
int k,n,m,i,j,max;
int a[600],d[600];
scanf("%d",&k);
while(k--)
{
scanf("%d",&m);
for(i=1; i<=m; i++)
scanf("%d",&a[i]);
scanf("%d",&n);
for(j=1; j<=n; j++)
scanf("%d",&d[j]);
memset(f,0,sizeof(f));
for(i=1; i<=m; i++)
{
max=0;
for(j=1; j<=n; j++)
{
f[i][j]=f[i-1][j];
if(a[i]>d[j]&&max<f[i-1][j])
max=f[i-1][j];
if(a[i]==d[j])
f[i][j]=max+1;
}
}
max=0;
for(i=1; i<=n; i++)
if(max<f[m][i])
max=f[m][i];
printf("%d\n",max);
if(k!=0)
printf("\n");
}
return 0;
}