1172.Queue
Description
On the PE,the teacher wants to choose some of n students to play games. Teacher asks n students stand in a line randomly(obviously,they have different height), then teacher tells someone to leave the queue(relative position is not change)to make the left students keep a special queue:
Assuming that the left students’ numbers are 1, 2,……, m from left to right and their height are T1,T2,……,Tm. Then they satisfy T1<T2<......<Ti, Ti>Ti+1>……>Tm (1<=i<=m).
Giving you the height of n students (from left to right), please calculate how many students left at most if you want to keep such a special queue.
Input
The first line contains an integer n (2<=n<=1000) represents the number of students.
The second line contains n integers Ti(150<=Ti<=200) separated by spaces, represent the height(cm) of student i.
One integer represents the number of the left students.
8
186 180 150 183 199 130 190 180
Sample Output
5
题意就是说有一排人站着,从里面出来几个人之后,剩下的人可以做到身高前面严格递增然后后面严格递减(T1<T2<......<Ti, Ti>Ti+1>……>Tm),问最多可以留几个人。这题做法就是把所有人前面的最长递增子序列和后面的最长递减子序列都算出来,然后两个序列长度加起来-1(因为自身加了两次)。都算完之后得到的最大的那个数就是最后的答案了。
表示这个题是队里选拔赛的一道题= =因为没有模板一开始nlogn算法写错了,所以想着先用n^2的算法试一下,如果超时再改。结果一直WA.....后来师哥说这题评测有问题,重新评测之后TLE了.....不早说= =然后又凭自己记忆把nlogn算法改出来总算是AC了.......
下面是AC代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int a[1005];
int maxlen[1005];
int b1[1005],b2[1005];
int len[1005];
int c[1005];
int max(int x,int y)
{
return x>y?x:y;
}
int fin(int *t,int len,int x)
{
int left=0;
int right=len;
int mid=(left+right)/2;
while(left<=right)
{
if(x>t[mid])
left=mid+1;
else if(x<t[mid])
right=mid-1;
else
return mid;
mid=(left+right)/2;
}
return left;
}
int main()
{
int n;
int i,j,k,e;
int len1,len2;
while(scanf("%d",&n)!=EOF)
{
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
e=0;
//分段处理
for(k=1;k<=n;k++)
{
//对前半段
memset(c,0,sizeof(c));
for(i=1;i<=k;i++)
{
b1[i]=a[i];
}
c[1]=-1;
c[2]=b1[1];
len1=0;
for(i=1;i<=k;i++)
{
j=fin(c,len1,b1[i]);
c[j]=b1[i];
if(j>len1)
len1=j;
}
//cout<<len1<<endl;
//对后半段
memset(c,0,sizeof(c));
for(i=n,j=1;i>=k;i--,j++)
{
b2[j]=a[i];
//cout<<b2[j]<<endl;
}
c[1]=-1;
c[2]=b1[1];
len2=0;
for(i=1;i<=n-k+1;i++)
{
j=fin(c,len2,b2[i]);
c[j]=b2[i];
if(j>len2)
len2=j;
}
//cout<<len2<<endl;
len[e]=len1+len2-1;
e++;
}
cout<<*max_element(len,len+n)<<endl;
}
return 0;
}