Greatest Common Increasing Subsequence
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 6 Accepted Submission(s) : 1
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
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
ACM暑期集训队练习赛(二)
总结:
这道题还是有点意思的,首先宏观的思路是最长公共子序列的的思想,思路是这样的,如果两个元素相等,那么就去找他前方最大的公共子序列,并且满足上升关系,同理。//
以上是第一次的思路,但是后来经过讨论发现,这道题远不止这么简单,我们既要考虑到最长子串的公共性,还要考虑到上升性,实质上我们的状态和之前的最长公共子序列已经有所不同了,状态定义的时候为了保证上升性,我们的f[i][j]其实是以a[i],b[j]为结尾的最长公共上升子序列了,
<pre name="code" class="cpp">#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std;
const int maxn=500+10;
int a[maxn],f[maxn][maxn],b[maxn];
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;
//scanf("%d",&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;
}