Wavio Sequence
Wavio is a sequence of integers. It has some interesting properties.
·
·
·
·
For example
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 :
Input
The input file contains less than
Each set starts with a postive integer,
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
Output for Sample Input
9
9
1
题意: 在一组序列中, 找出一组序列长度为奇数(2*n+1), 前面n+1个严格递增, 后面n+1一个严格递减
求出最大满足这种序列的长度.
解题思路:
1. 我并不知道这种序列有什么好算法求解, 但是经典问题求最长升序序列, 这样我们的问题
可以变成同时从原序列两个方向求解最长升序序列. 只是方向不同而已.
2. 回顾下最长序列求法, 复杂度为O(n*logn)的算法.
for(int i = 1; i <= n; ++i)
int index = binarySearch(a[i], g); // 在g[1]~g[n]中查找a[i]返回下标.
dp[i] = k;
g[k] = a[i];
显然结果是max(dp[i]);
代码:
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
#define MAX 10005
int n;
int a[MAX];
int list1[MAX], list2[MAX];
int ans1[MAX], ans2[MAX];
inline int min(int a, int b)
{
return a < b ? a : b;
}
inline int max(int a, int b)
{
return a > b ? a : b;
}
int binarySearch(int left, int right, int cur, int *b)
{
while(left < right)
{
int mid = (left+right)/2;
if( b[mid] < cur ) left = mid+1;
else right = mid;
}
return left;
}
int main()
{
//freopen("input.txt", "r", stdin);
int i;
while(scanf("%d", &n) != EOF)
{
for(i = 1; i <= n; ++i)
scanf("%d", &a[i]);
int index1 = 0, index2 = 0;
int tempindex1 = 0, tempindex2 = 0;
for(i = 1; i <= n; ++i)
{
tempindex1 = binarySearch(1, index1+1, a[i], list1);
tempindex2 = binarySearch(1, index2+1, a[n-i+1], list2);
index1 = max(tempindex1, index1);
index2 = max(tempindex2, index2);
ans1[i] = tempindex1;
ans2[n-i+1] = tempindex2;
list1[tempindex1] = a[i];
list2[tempindex2] = a[n-i+1];
}
int ans = 1;
for(i = 1; i <= n; ++i)
ans = max(ans, min(ans1[i], ans2[i])*2-1);
printf("%d\n", ans);
}
return 0;
}