Longest Ordered Subsequence
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 Source
Northeastern Europe 2002, Far-Eastern Subregion
|
简单动态规划,最长上升子序列基础模板题。虽是入门级,但也很重要,能够帮助理解LIS算法的基本原理,下面列出两种方法;
时间复杂度n^2:
#include<cstdio> #include<iostream> #include<algorithm> #include<cmath> using namespace std; int a[1010],dp[1010]; int main() { int n; while(scanf("%d",&n)!=EOF) { for(int i=0; i<n; i++) { scanf("%d",&a[i]),dp[i]=1; } if(!n){ printf("1\n"); continue; } int ans=1; for(int i=1;i<n;i++){ for(int j=0;j<i;j++){ if(a[i]>a[j]) dp[i]=max(dp[i],dp[j]+1); } ans=max(ans,dp[i]); } printf("%d\n",ans); } return 0; }
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
以下nlogn复杂度这种挺巧妙的,以下是学习了大牛的写法后写下的代码理解一下就会发现其中的美。
尊重原创:原创链接:http://blog.sina.com.cn/s/blog_76344aef0100scyq.html
nlogn复杂度:
</pre><pre name="code" class="cpp">#include<cstdio> #include<iostream> #include<algorithm> #include<cmath> #include<cstring> using namespace std; int a[1010],dp[1010]; int sorce(int l,int r,int t) { int mid=l+r>>1; if(l==r) return l; if(t>dp[mid]) return sorce(mid+1,r,t); else return sorce(l,mid,t); } int main() { int n; while(scanf("%d",&n)!=EOF) { for(int i=0; i<n; i++) { scanf("%d",&a[i]); } dp[0]=-1; int len=0,j; for(int i=0; i<n; i++) { if(a[i]>dp[len]) dp[++len]=a[i]; else { j=sorce(1,len,a[i]); dp[j]=a[i]; } } printf("%d\n",len); } return 0; }