您的位置:首页 > 产品设计 > UI/UE

ACM: uva 10534 - Wavio Sequence

2016-05-19 23:29 477 查看
Wavio
Sequence
 

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

 

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
中查找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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: