(DP LIS) POJ2533 Longest Ordered Subsequence

mac2022-06-30  105

Longest Ordered Subsequence Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 66763 Accepted: 29906

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最长递增子序列问题,水题。理解好状态转移式怎么得到就行了。状态转移式是d(i) = max(dp[j] + 1,dp[i])(a[i] > a[j])(j < i) (如果为最长不下降子序列的话a[i] >= a[j]就行,并且j < i);其中dp[i]要先为1,因为无论如何这个子序列的长度的最小情况为1。打表就行对了,最后得到的dp[i]中i从1到n时,各自的dp[i]代表前i个数的最长递增子序列的最长长度。不一定dp[n]是最大的,要先比较,从中选出最大的。C++ 代码: #include<iostream> #include<cstring> #include<algorithm> #include<cstdio> using namespace std; const int maxn = 1005; int a[maxn],dp[maxn]; int main(){ int n; memset(a,0,sizeof(a)); scanf("%d",&n); for(int i = 0; i < n; i++){ cin>>a[i]; } memset(dp,0,sizeof(dp)); for(int i = 0; i < n; i++){ dp[i] = 1; for(int j = 0; j < i; j++){ if(a[i] > a[j] && dp[j] + 1 > dp[i]) dp[i] = dp[j] + 1; } } int ans = -1; for(int i = 0; i < n; i++){ ans = max(ans,dp[i]); } printf("%d\n",ans); return 0; }

 

转载于:https://www.cnblogs.com/Weixu-Liu/p/10511265.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)