您的位置:首页 > 产品设计 > UI/UE

Longest Ordered Subsequence (最长上升子序列)

2015-02-06 14:07 183 查看
Description

Anumericsequenceofaiisorderedifa1<a2<...<aN.Letthesubsequenceofthe
givennumericsequence(a1,a2,...,aN)beanysequence(ai1,ai2,
...,aiK),where1<=i1<i2<...<iK<=N.Forexample,
sequence(1,7,3,5,9,4,8)hasorderedsubsequences,e.g.,(1,7),(3,4,8)andmanyothers.Alllongestorderedsubsequencesareoflength4,e.g.,(1,3,5,8).

Yourprogram,whengiventhenumericsequence,mustfindthelengthofitslongestorderedsubsequence.

Input

ThefirstlineofinputfilecontainsthelengthofsequenceN.Thesecondlinecontainstheelementsofsequence-Nintegersintherangefrom0to10000each,separatedbyspaces.1<=N<=1000

Output

Outputfilemustcontainasingleinteger-thelengthofthelongestorderedsubsequenceofthegivensequence.

SampleInput

7
1735948


SampleOutput

4


#include<stdio.h>
intzhan[1000];
intmain()
{
intn,a,l,top;
scanf("%d",&n);
top=0;
zhan[0]=-1;//第一个元素可能为0,所以栈底设为-1
for(inti=0;i<n;i++)
{
scanf("%d",&a);
if(a>zhan[top])
{
zhan[++top]=a;
}
else
{
intlow=1,high=top;//栈的最底端是1,最上面是top
intmid;
while(low<=high)//利用二分法查找在栈中比a大的第一个数
{
mid=(low+high)/2;
if(a>zhan[mid])
{
low=mid+1;
}
else
{
high=mid-1;
}
}
zhan[low]=a;//找到了就替换啊
}
}
printf("%d\n",top);//top是最顶端的,top是几就代表那个序列多长
return0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: