ACM: uva 10534 - Wavio Sequence

来源:互联网 发布:网络延迟多少ms算正常 编辑:程序博客网 时间:2024/05/17 00:11

WavioSequence 

Wavio is a sequence of integers. It has some interestingproperties.

·  Wavio is ofodd length i.e. L = 2*n + 1.

·  Thefirst (n+1) integers ofWavio sequence makes a strictly increasing sequence.

·  Thelast (n+1) integers ofWavio sequence makes a strictly decreasing sequence.

·  No twoadjacent integers are same in a Wavio sequence.

For example 1, 2, 3, 4, 5, 4, 3, 2,0 is an Wavio sequence oflength 9. But 1, 2, 3,4, 5, 4, 3, 2, 2 is not a valid waviosequence. In this problem, you will be given a sequence ofintegers. You have to find out the length of the longest Waviosequence 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 54 3 2 1. So, the output will be 9.

 

Input

The input file contains lessthan 75 test cases. Thedescription of each test case is given below: Input is terminatedby end of file.

 

Each set starts with a postiveinteger, N(1<=N<=10000).In next few lines there willbe N integers.

 

Output

For each set of input print the length of longest wavio sequencein 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;
}
0 0
原创粉丝点击