[动态规划]之裸lis之最长上升子序列POJ 2533

一、乱喷

昨天华中农业大学网赛,又是只写了写水题,还发生了些戏剧性的事情。最后一题没时间看,今天看了看,本来想写,发现考的是最长上升等差子序列数列的长度,递增的还不会,就问了问宋大神,就先看了看最长上升子序列。

二、Lis

时间复杂度(n^2)                               ----(优化方法回头补上)

我的理解:例子    a[i]   标号从1-n;

{2,1,5,3,6,4,8}

dp[i]数组存的是 第i个数的最长上升子序列的长度。

步骤:

1.对于{2}来说,dp[1]=1,也就是最长上升子序列长度为1.

2.对于{2,1},首先我们比较a[1]与a[2]大小

若a[1]>a[2] ,此时一个最长子序列的长度仍然为1,即dp[2]=1.

若a[1]<a[2],则可以看出a[1],a[2] 是递增的,所以dp[2]=dp[1]+1;

3.对于{2,1,5}

这时候a[3]要分别与a[1],a[2] 比较大小。

a[3]>a[1],由于子序列可以是不连续的,故{a[1],a[3]}可以是一个子序列,dp[3]=dp[1]+1

a[3]>a[2],说明以a[2]为末端的子序列(可以不连续哦)+a[3]能形成一个新的子序列,此时要给dp[3]赋值,

重点来了,dp[3]是等于dp[2]+1还是等于dp[1]+1

既然求最长  当然是dp[3]=max(dp[1],dp[2])+1

当 a[3]即小于a[1]又小于a[2]的时候 dp[3]=1

例子中dp[3]=max(dp[1],dp[2])+1=1+1=2;

...

这样问题就可以总结为:

在dp[1],dp[2],dp[3]...dp[n-1]的情况下求dp[n]

若a[n]>a[1],a[n]>a[2],a[n]>a[3]….,

dp[n]=max{dp[1],dp[2],dp[3],,,,,,}+1

若不满足

dp[n]=1;

 

题目:

Longest Ordered Subsequence

Time Limit: 2000 MS Memory Limit: 65536 KB

64-bit integer IO format: %I64d , %I64u Java class name: Main

[Submit] [Status] [Discuss]

Description

A numericsequence of ai is orderedif a1 < a2 < ...< aN. Let thesubsequence of the given numeric sequence (a1a2, ..., aN) be anysequence (ai1ai2, ..., aiK), where 1 <= i1 < i2 < ...< iK <= N.For example, sequence (1, 7, 3, 5, 9, 4, 8) has ordered subsequences, e. g.,(1, 7), (3, 4, 8) and many others. All longest ordered subsequences are oflength 4, e. g., (1, 3, 5, 8).

Your program, when given the numeric sequence, must find the length of itslongest ordered subsequence.

Input

The first lineof input file contains the length of sequence N. The second line contains theelements of sequence - N integers in the range from 0 to 10000 each, separatedby spaces. 1 <= N <= 1000

Output

Output file mustcontain a single integer - the length of the longest ordered subsequence of thegiven sequence.

Sample Input

7

1 7 3 5 9 4 8

Sample Output

4

Source

NortheasternEurope 2002, Far-Eastern Subregion

 AC code

#include<cstdio>
#include<string.h>
#include<math.h>
#include<algorithm>

using namespace std;

int a[1005],dp[1005];

int lis(int n)
{
	int i,j,max;
	int ans=1;
	dp[1]=1;
	for(i=2;i<=n;i++)
	{
		max=0;
		for(j=1;j<=i;j++)
		{
			if(max<dp[j]&&a[j]<a[i])
				max=dp[j];
		}
		dp[i]=max+1;   //若for(j)中的条件不成立。也就是说a[i]比前边的数都大 所以dp[i]=0+1; 
		if(dp[i]>ans)
		ans=dp[i];
	}
	return ans;
}

int main()
{
	int t,i;
	while(scanf("%d",&t)!=EOF)
	{
		memset(dp,0,sizeof(a));
		for(i=1;i<=t;i++)
			scanf("%d",a+i);
		int ans=lis(t);
		printf("%d\n",ans);
	}
	
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值