Longest Ordered Subsequence
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 54789 | Accepted: 24545 |
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.
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
最长上升子序列,简单dp,O(n*n)就可以过
O(n*n)代码:
#include <cstdio>
#include <iostream>
#include <cmath>
#include <cstring>
#include <string>
#include <stack>
#include <queue>
#include <algorithm>
#include <map>
#define ll long long
#define inf 1e18+5
using namespace std;
int a[1010],dp[1010],n;
int main(){
while(~scanf("%d",&n)){
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
int mmax;
for(int i=0;i<=n;i++)
dp[i]=0;
dp[1]=1;
for(int i=2;i<=n;i++){
mmax=0;
for(int j=1;j<i;j++){
if(a[j] < a[i] && mmax < dp[j])
mmax=dp[j];
}
dp[i]=mmax+1;
}
mmax=0;
for(int i=1;i<=n;i++){
mmax=max(mmax,dp[i]);
}
printf("%d\n",mmax);
}
return 0;
}
n*log(n)代码:
#include <cstdio>
#include <iostream>
#include <cmath>
#include <cstring>
#include <string>
#include <stack>
#include <queue>
#include <algorithm>
#include <map>
#define ll long long
#define inf 1e18+5
using namespace std;
int a[1010],dp[1010],n;
int bin(int len,int k){
int l=1,r=len;
while(l <= r){
int mid=(l+r)/2;
if(k > dp[mid]){
l=mid+1;
}
else
r=mid-1;
}
return l;
}
int main(){
while(~scanf("%d",&n)){
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
int mmax;
for(int i=0;i<=n;i++)
dp[i]=0;
dp[1]=a[1];
int ans=1,j;
for(int i=2;i<=n;i++){
if(a[i] <= dp[1])
j=1;
else if(a[i] > dp[ans])
j=++ans;
else
j=bin(ans,a[i]);
dp[j]=a[i];
}
/*mmax=0;
for(int i=1;i<=n;i++){
mmax=max(mmax,dp[i]);
}*/
printf("%d\n",ans);
}
return 0;
}