经典动态规划问题--最长上升子序列 POJ--2533

Longest Ordered Subsequence

Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 30869   Accepted: 13465

Description

A numeric sequence of ai is ordered if a1 < a2 < ... < aN. Let the subsequence of the given numeric sequence ( a1, a2, ..., aN) be any sequence ( ai1, ai2, ..., 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 of length 4, e. g., (1, 3, 5, 8).

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

Input

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

Output

Output file must contain a single integer - the length of the longest ordered subsequence of the given sequence.

Sample Input

7
1 7 3 5 9 4 8

Sample Output

4

解题思路:这一题刚开始有点卡住了,可能最近相同类型的题目做的有点多。最后看了提示想到的方法,不用递归去做。原题中要我们求解最大上升子序列,那么我们可以把问题分解为以求第 i 个数为结尾的子序列的最大上升子序列。而第i个数的解和前面i-1个数的解是存在联系的,这就是解题的核心。知道前面i-1个数的解后来求第i个数,我们只要和前面i-1个数相比找到比第i个数小且其解最大的值max,max+1就是第i个数的解!

 

// 最长上升子序列.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include
#include
#include
#include
using namespace std;
int a[1010]={0};
int len_[1010]={0};

int main()
{
	int n=0;
	int max_=0;
	while(scanf("%d",&n)!=EOF)
	{
		int i=0;
		max_=0;

		memset(a,0,sizeof(a));
		for(i=0;ia[j])
				  {
					  len_[i]=max(len_[j]+1,len_[i]);
				  }
					 
	
		for(i=0;imax_)
				max_=len_[i];
		printf("%d\n",max_);
		
	}
	return 0;
}


 

你可能感兴趣的:(数据结构,算法,c语言,c++,c++,c语言,动态规划)