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
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
Sample Output
9
9
1
分析:
可以先求出这个序列的最长子序列,并记录每一个数最长子序列。
同理,再倒序求出序列的最长子序列,并记录每一个数最长子序列。
这时候在遍历一遍每个数,结果即为max(min(a[i]的最长增长子序列,a[i]的最长递减子序列)*2-1);理由不言而喻。
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<algorithm>
using namespace std;
int n,a[10002],d[10002],w[10002],ad[10002],ad2[10002],sum,len,l2;
int erfen(int q[],int l,int r,int k) //二分法
{
int m;
while(l<=r)
{
m=(l+r)/2;
if(q[m]==k) //寻找相同的数据
return m;
else if(q[m]>k)
r=m-1;
else
l=m+1;
}
return l;
}
int main()
{
int we,i,j;
while(scanf("%d",&n)!=EOF)
{
for(i=1; i<=n; i++)
scanf("%d",&a[i]);
sum=len=ad[1]=1;
d[len]=a[1];
for(i=2; i<=n; i++) //正序找到每个数的最长递增序列长度
{
if(a[i]>d[len])
{
d[++len]=a[i]; //递增序列
ad[i]=len; //递增序列长度
}
else
{
we=erfen(d,1,len,a[i]); //二分法,寻找序列中的位置
d[we]=a[i];
ad[i]=we;
}
}
l2=1;
w[l2]=a[n];
ad2[n]=1;
for(i=n-1; i>=1; i--) //寻找最长递减子序列
{
if(a[i]>w[l2])
{
w[++l2]=a[i]; //递减序列
ad2[i]=l2; //递减序列长度
}
else
{
we=erfen(w,1,l2,a[i]); //二分查找在序列中的位置
w[we]=a[i];
ad2[i]=we;
}
}
for(i=1; i<=n; i++)
sum=max(sum,(min(ad[i],ad2[i])*2-1));//寻找最长的递增递减子序列
printf("%d\n",sum);
}
return 0;
}