POJ 2533 Longest Ordered Subsequence(最长路径 dp)

来源:互联网 发布:十大网络主播评选排名 编辑:程序博客网 时间:2024/05/20 23:02

Longest Ordered Subsequence
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 49925 Accepted: 22167

Description

A numeric sequence of ai is ordered if a1 < a2 < ... < aN. Let the subsequence of the given numeric sequence (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) 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

71 7 3 5 9 4 8

Sample Output

4

题意很简单,求最长递增子序列的个数;

这题我用的方法是: 未给定起点和终点的最长路解法(DAG上的动态规划),算法复杂度比(nlogn算法 稍微差点,因为hdu1025、1950用的这种方法解,本题就换了种做法)。用到了记忆化搜索 避免超时。

AC代码如下:

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int maxn=1000+10;int d[maxn];int v[maxn];int n;int dp(int i){int& ans=d[i];if(ans>0)return ans;ans=1;for(int j=i+1;j<n;j++){if(v[i]<v[j])   ans=max(ans,dp(j)+1);}return ans;}int main(){while(scanf("%d",&n)==1){for(int i=0;i<n;i++) scanf("%d",&v[i]); memset(d,0,sizeof(d)); int ans=0; for(int i=0;i<n;i++){ ans=max(ans,dp(i)); } printf("%d\n",ans);}return 0;}




1 0
原创粉丝点击