Longest Ordered Subsequence

来源:互联网 发布:eviews怎么导入数据 编辑:程序博客网 时间:2024/05/17 03:12
8596 Longest Ordered Subsequence
时间限制:300MS 内存限制:1000K 提交次数:53 通过次数:24
语言: not limited
描述
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.
输入格式
There are several test cases. Every test case includes two lines.
The first line 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
When N is 0, it indicates test to end.
输出格式
Output must contain a single integer for every test case ---- the length of the longest ordered subsequence of the given sequence.
输入样例
7
1 7 3 5 9 4 8
6
1 8 3 6 5 9
5
1 2 3 4 5
0
输出样例
4
4
5
Hint
15
这道题的输入输出和别的题不同,此题输入包含多组测试数据,而不是只有一组,以0判断结束。
大家在接受数据的时候,不要用getchar()这个函数,这个函数在你本机不会有问题,但OJ系统中会有错误出来。
接受数据用scanf的%d,或cin等,会自动判别回车字符的,不要在你程序里判别回车字符。
对于最后一组数据输入为0表示结束,只要判断接受的是否为0就结束,无须去处理回车字符。
考虑采用动态规划算法,针对每个元素,以该元素结尾的最长有序子序列作为子问题,
计算出每个子问题的最大长度用“表”记录下来。先写出递推关系式再编程实现。
设f(i)表示:从左向右扫描过来直到以a[i]元素结尾的序列,可获得的最长上升子序列的长度,且子序列包含a[i]元素(1<=i<=n)。
f(i)是从f(1),f(2), ……到f(i-1)中找最大的一个值,再加1。或者就是1。
这主要得看a[i]这个元素能否加入到之前已经获得的最长上升子序列当中去,
如果能加入,是之前已获得的最长上升子序列长度加一;
如果不能加入,就开始一个新的上升子序列,长度为1。
最后,所要求的整个序列的最长上升子序列长度为max{f(i): 1<=i<=n}
f(i)的递推公式如下:
1)f(i)=1 当i=1;
2)f(i)=max{f(j)+1} 当a[i]>a[j],j大于等于1且小于i,i>1;
3)f(i)=1 当对任意j,(j大于等于1且小于i),都有a[i]<=a[j];
例子,对于序列:4 2 6 3 1 5 2
i = 1 2 3 4 5 6 7
a[i]= 4 2 6 3 1 5 2
f(i)= 1 1 2 2 1 3 2

这里max{f(i)}=3为原问题所求的最长上升子序列的长度。



--------------------------------------------------------------------

8596  Longest Ordered Subsequence       (动态规划)

#include<stdio.h>

#include"malloc.h"

#include"string.h"

int F(int *a,int *f, int n)

{  

int length,i,count=0;

if(n==0) return 1;

if(n>0)

{

length=1;//if((a[n]<=a[i])

for(i=n-1;i>=0;i--)

{

if((a[n]>a[i]))

{length=f[i]+1; break;}

}

}

return length;

}

int main()

{

int n,i,*f,*a,length;

while(1)

{

scanf("%d",&n);

if(n==0) break;

length=1;

a=(int*)malloc(n*sizeof(int));

f=(int*)malloc(n*sizeof(int));

for(i=0;i<n;i++)

scanf("%d",&a[i]);

for(i=0;i<n;i++)

{

f[i]=F(a,f,i);

if(length<f[i])

length=f[i];

}

printf("%d\n",length);

}

return 0;

}



原创粉丝点击