Longest Ordered Subsequence
Time Limit: 2000MS |
|
Memory Limit: 65536K |
Total Submissions: 21310 |
|
Accepted: 9190 |
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
最長上升子序列
樸素的做法n^2的復雜度,n<=1000不會超時
有nlogn的做法
1
/**///////樸素做法 2
#include<stdio.h>
3
#include<string.h>
4
#include<math.h>
5
#define MAX 1005
6
int a[MAX],f[MAX];
7
int n,i,j,ans;
8
int max(int a,int b)
9

{
10
if (a>b) return a; else return b;
11
}
12
int main()
13

{
14
scanf("%d",&n);
15
for (i=1;i<=n ;i++) scanf("%d",&a[i]);
16
f[1]=1;
17
ans=f[1];
18
for (i=2;i<=n ;i++ )
19
{
20
f[i]=1;
21
for (j=1;j<=i-1 ;j++ )
22
{
23
if (a[j]<a[i])
24
{
25
f[i]=max(f[i],f[j]+1);
26
}
27
}
28
ans=max(ans,f[i]);
29
}
30
printf("%d\n",ans);
31
return 0;
32
}
優化的解法 nlogn
1
/**/////二分查找優化 nlogn 2
#include<stdio.h>
3
#include<string.h>
4
#include<math.h>
5
#define MAX 1005
6
int f[MAX];
7
int i,j,ans,n;
8
int left,right,x,mid;
9
int main()
10

{
11
scanf("%d",&n);
12
ans=0;
13
for (i=1; i<=n ; i++)
14
{
15
scanf("%d",&x);
16
left=1;
17
right=ans;
18
while (left<right)
19
{
20
mid=(left+right)/2;
21
if (f[mid]<x) left=mid+1;
22
else right=mid;
23
}
24
if (left>=right&&x>f[ans]||ans==0)
25
{
26
ans++;
27
f[ans]=x;
28
}
29
else if (x<f[left])
30
{
31
f[left]=x;
32
}
33
}
34
printf("%d\n",ans);
35
return 0;
36
}