| Time Limit: 10000MS | Memory Limit: 65536K | |
| Total Submissions: 9193 | Accepted: 2427 | |
| Case Time Limit: 2000MS | Special Judge |
Description
You are given two sequences of integer numbers. Write a program to determine their common increasing subsequence of maximal possible length.
Sequence S 1 , S 2 , . . . , S N of length N is called an increasing subsequence of a sequence A 1 , A 2 , . . . , A M of length M if there exist 1 <= i 1 < i 2 < . . . < i N <= M such that S j = A ij for all 1 <= j <= N , and S j < S j+1 for all 1 <= j < N .
Sequence S 1 , S 2 , . . . , S N of length N is called an increasing subsequence of a sequence A 1 , A 2 , . . . , A M of length M if there exist 1 <= i 1 < i 2 < . . . < i N <= M such that S j = A ij for all 1 <= j <= N , and S j < S j+1 for all 1 <= j < N .
Input
Each sequence is described with M --- its length (1 <= M <= 500) and M integer numbers A
i (-2
31 <= A
i < 2
31 ) --- the sequence itself.
Output
On the first line of the output file print L --- the length of the greatest common increasing subsequence of both sequences. On the second line print the subsequence itself. If there are several possible answers, output any of them.
Sample Input
5 1 4 2 5 -12 4 -12 1 2 4
Sample Output
2 1 4
最长递增公共子序列
状态转移方程:
a[i]==b[j]时,dp[i][j]=dp[i-1][j-1]+1;
a[i]!=b[j]时,dp[i][j]=Max(dp[i-1][j],dp[i][j]);
#include"stdio.h"
#include"string.h"
#define N 505
int dp[N][N],pre[N][N];
#define Max(x,y) ((x)>(y)?(x):(y))
int main()
{
int i,j,n,m;
int a[N],b[N];
int ans[N];
while(scanf("%d",&n)!=-1)
{
for(i=0;i<n;i++)
scanf("%d",&a[i]);
scanf("%d",&m);
for(i=0;i<m;i++)
scanf("%d",&b[i]);
memset(dp,0,sizeof(dp));
memset(pre,0,sizeof(pre));
memset(ans,0,sizeof(ans));
for(i=0;i<n;i++)
{
int t=0,max=0;
for(j=0;j<m;j++)
{
if(a[i]==b[j])
{
dp[i][j]=max+1;
pre[i][j]=t;
}
else
dp[i][j]=Max(dp[i][j],dp[i-1][j]);
if(a[i]>b[j]&&dp[i][j]>max)
{
max=dp[i][j];
t=j;
}
}
}
int x=n-1,k=0,y,cnt=0;
for(i=0;i<n;i++)
for(j=0;j<m;j++)
if(cnt<dp[i][j])
{
cnt=dp[i][j];
y=j;
}
printf("%d\n",cnt);
while(cnt--)
{
ans[k++]=b[y];
while(a[x]!=b[y])
x--;
y=pre[x][y];
x--;
}
for(i=k-1;i>=0;i--)
printf("%d ",ans[i]);
printf("\n");
}
return 0;
}
本文介绍了一种求解两个整数序列的最长递增公共子序列问题的算法实现,通过动态规划方法寻找序列间的递增公共部分,并给出具体代码示例。
&spm=1001.2101.3001.5002&articleId=24389045&d=1&t=3&u=69df811c380143c3beac518d56a9fa20)
74

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



