POJ 2533: Longest Ordered Subsequence (最大上升子列)

题目来源:http://poj.org/problem?id=2533

Longest Ordered Subsequence

Time Limit: 2000MS

Memory Limit: 65536K

Description

A numeric sequence of ai isordered if a1 < a2 <... < aN. Let the subsequence of the given numericsequence (a1a2, ..., aN)be any sequence (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) andmany 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 itslongest ordered subsequence.

Input

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

Output

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

Sample Input

7
1 7 3 5 9 4 8

SampleOutput

4

Source

Northeastern Europe 2002,Far-Eastern Subregion

-----------------------------------------------------

解题思路

1. c[i]表示以i为开头的最大上升子串长度,在c[i]中取最大即得解

2. 对每个c[i]d[j]表示以i为开头、以j为结尾的最大上升子串,c[i] = max(d[j])

-----------------------------------------------------

代码

//1759:最长上升子序列
//总时间限制: 2000ms 内存限制: 65536kB
//描述
//一个数的序列bi,当b1 < b2 < ... < bS的时候,我们称这个序列是上升的。对于给定的一个序列(a1, a2, ..., aN),我们可以得到一些上升的子序列(ai1, ai2, ..., aiK),这里1 <= i1 < i2 < ... < iK <= N。比如,对于序列(1, 7, 3, 5, 9, 4, 8),有它的一些上升子序列,如(1, 7), (3, 4, 8)等等。这些子序列中最长的长度是4,比如子序列(1, 3, 5, 8).
//
//你的任务,就是对于给定的序列,求出最长上升子序列的长度。
//输入
//输入的第一行是序列的长度N (1 <= N <= 1000)。第二行给出序列中的N个整数,这些整数的取值范围都在0到10000。
//输出
//最长上升子序列的长度。
//样例输入
//7
//1 7 3 5 9 4 8
//样例输出
//4

#include<fstream>
#include<iostream>
using namespace std;

int arr[1001] = {};
int n = 0;

int cal(int m)							// 以arr[m]为开头的最长上升子序列的长度
{
	int dp[1001] = {};					// 以arr[m]为开头,以arr[i]为结尾的最长上升子序列长度
	int i = m, j = m, mymax = 0;
	dp[m] = 1;
	if (m==n-1)
	{
		return 1;
	}
	else
	{
		for (i=m+1; i<n; i++)
		{
			mymax = 0;
			for (j=m; j<i; j++)
			{
				if (arr[j]<arr[i])
				{
					mymax = (dp[j]+1)>mymax? (dp[j]+1):mymax;	// 每个dp[i]取最大
				}
			}
			dp[i] = mymax;
		}
		mymax = 0;
		for (i=m; i<n; i++)
		{
			mymax = dp[i]>mymax? dp[i]:mymax;					// 在dp[i]里取最大
		}
		return mymax;
	}
}


int main()
{
#ifndef ONLINE_JUDGE
	ifstream fin("0206_1759.txt");
	int i;
	fin >> n;
	for (i=0; i<n; i++)
	{
		fin >> arr[i];
	}
	fin.close();
	int mymax = 0, theans = 0;
	for (i=0; i<n; i++)
	{
		theans = cal(i);
		mymax = mymax>theans? mymax:theans;
	}
	cout << mymax;
	return 0;
#endif
#ifdef ONLINE_JUDGE
	int i;
	cin >> n;
	for (i=0; i<n; i++)
	{
		cin >> arr[i];
	}
	int mymax = 0, theans = 0;
	for (i=0; i<n; i++)
	{
		theans = cal(i);
		mymax = mymax>theans? mymax:theans;
	}
	cout << mymax;
	return 0;
#endif
}


猜你喜欢

转载自blog.csdn.net/da_kao_la/article/details/80514363