hdu1423 Greatest Common Increasing Subsequence 最长公共上升子序列 模板题

Greatest Common Increasing Subsequence

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


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
 
  
151 4 2 5 -124-12 1 2 4
 

Sample Output
 
  
2
 

Source
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<iostream>
using namespace std;
const int maxn=510;
int a[maxn],f[maxn][maxn],b[maxn];
//我们既要考虑到最长子串的公共性,还要考虑到上升性,实质上我们的状态和之前的最长公共子序列已经有所不同了,
//状态定义的时候为了保证上升性,我们的f[i][j]其实是以a[i],b[j]为结尾的最长公共上升子序列了,

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;
}




猜你喜欢

转载自blog.csdn.net/cao2219600/article/details/79926107