Wavio Sequence
Input: Standard Input
Output: Standard Output
Time Limit: 2 Seconds
Wavio is a sequence of integers. It has some interesting properties.
· Wavio is of odd length i.e. L = 2*n + 1.
· The first (n+1) integers of Wavio sequence makes a strictly increasing sequence.
· The last (n+1) integers of Wavio sequence makes a strictly decreasing sequence.
· No two adjacent integers are same in a Wavio sequence.
For example 1, 2, 3, 4, 5, 4, 3, 2, 0 is an Wavio sequence of length 9. But 1, 2, 3, 4, 5, 4, 3, 2, 2 is not a valid wavio sequence. In this problem, you will be given a sequence of integers. You have to find out the length of the longest Wavio sequence which is a subsequence of the given sequence. Consider, the given sequence as :
1 2 3 2 1 2 3 4 3 2 1 5 4 1 2 3 2 2 1.
Here the longest Wavio sequence is : 1 2 3 4 5 4 3 2 1. So, the output will be 9.
Input
The input file contains less than 75 test cases. The description of each test case is given below: Input is terminated by end of file.
Each set starts with a postive integer, N(1<=N<=10000). In next few lines there will be N integers.
Output
For each set of input print the length of longest wavio sequence in a line.
Sample Input Output for Sample Input
10 1 2 3 4 5 4 3 2 1 10 19 1 2 3 2 1 2 3 4 3 2 1 5 4 1 2 3 2 2 1 5 1 2 3 4 5 | 9 9 1
|
Problemsetter: Md. Kamruzzaman, Member of Elite Problemsetters' Panel
看师姐的代码一个多小时才看懂,然后自己码了一个。动态规划真心伤不起。
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int a,b,m;
int x[10007],y[10007],dp1[10007],dp2[10007];
int min(int a1,int b1)
{
return a1<b1?a1:b1;
}
void ddp(int dp[],int z[])
{
int top=0;
int stack[10007];
stack[top]=-10000007;
for(b=1;b<=m;b++)
{
if(z[b]>stack[top])
{
stack[++top]=z[b];
dp[b]=top;
}
else
{
int l=1,r=top;
while(l<=r)//用二分法查找第一个比啊a[i]大的元素
{
int mid=(l+r)>>1;
if(z[b]>stack[mid])
{
l=mid+1;
}
else r=mid-1;
}
stack[l]=z[b];
dp[b]=l;
}
}
}
int main()
{
while(scanf("%d",&m)!=EOF)
{
//memset(dp1,0,sizeof(dp1));
//memset(dp2,0,sizeof(dp2));
for(a=1;a<=m;a++)
{
scanf("%d",&x[a]);
y[m-a+1]=x[a];
dp1[a]=0;
dp2[a]=0;
}
ddp(dp1,x);
ddp(dp2,y);
int max=-1,count;
for(a=1;a<=m;a++)
{
count=min(dp1[a],dp2[m-a+1])*2-1;//因为要求递增序列与递减序列的个数相等,则取正反较小的一个
if(count>max)
{
max=count;
}
}
printf("%d\n",max);
}
return 0;
}