POJ 题目2127 Greatest Common Increasing Subsequence(LICS,输出路径)

本文介绍了一个经典的计算机科学问题——寻找两个整数序列之间的最长公共递增子序列,并提供了一段C语言实现的代码示例。该问题旨在通过算法找出两个序列中相同且递增的最长子序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Greatest Common Increasing Subsequence
Time Limit: 10000MS Memory Limit: 65536K
Total Submissions: 9762 Accepted: 2584
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 .

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

Source

Northeastern Europe 2003, Northern Subregion

ac代码

#include<stdio.h>
#include<string.h>
int n,m;
int dp[1010][1010],path[1010][1010],ans[1010],aj,ai,res,a[1010],b[1010];
void LCS()
{
	int i,j,mj;
	res=0;
	memset(dp,0,sizeof(dp));
	memset(path,-1,sizeof(path));
	for(i=1;i<=n;i++)
	{
		int ma=0;
		for(j=1;j<=m;j++)
		{
			dp[i][j]=dp[i-1][j];
			if(b[j]<a[i]&&dp[i][j]>ma)
			{
				ma=dp[i][j];
				mj=j;
			}
			else
			{
				if(b[j]==a[i])
				{
					dp[i][j]=ma+1;
					path[i][j]=mj;
				}
			}
			if(res<dp[i][j])
			{
				res=dp[i][j];
				ai=i;
				aj=j;
			}
		}
	}
}
int main()
{
	while(scanf("%d",&n)!=EOF)
	{
		int i,j;
		for(i=1;i<=n;i++)
			scanf("%d",&a[i]);
		scanf("%d",&m);
		for(j=1;j<=m;j++)
			scanf("%d",&b[j]);
		LCS();
		printf("%d\n",res);
		int temp=res;
		while(temp)
		{
			if(path[ai][aj]>-1)
			{
				ans[temp--]=b[aj];
				aj=path[ai][aj];
			}
			ai--;
		}
		for(i=1;i<=res;i++)
			printf("%d%c",ans[i],i==res?'\n':' ');
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值