UVa 10534 - Wavio Sequence

Contents

  1. 1. Problem
  2. 2. Solution
  3. 3. Code

Problem

中文網址

Solution

LIS 方法可參考 http://www.csie.ntnu.edu.tw/~u91029/LongestIncreasingSubsequence.html#3

做 LIS 和 LDS,比較每個數字在 LIS 串和 LDS 串中的位置,挑選位置相同且最長的。

    1 2 3 4 5 4 3 2 1 10

LIS 1 2 3 4 5 4 3 2 1 6
LDS 1 2 3 4 5 4 3 2 1 1 

其中最長的會是 min(LIS[4],LDS[4]) = 5,而其長度就是 5 * 2 - 1 = 9

這邊 LDS 的做法是採取從後面往前做 LIS。皆為 $O(nlogn)$ 。

Code

UVa 10534
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;

int main()
{
int n, num[10000], lis[10000], lds[10000];
vector<int> v;
while (scanf("%d", &n) != EOF)
{
int i;
for (i = 0; i < n; i++)
scanf("%d", &num[i]);

v.clear();
int size = 1;
v.push_back(num[0]);
lis[0] = 1;
for (i = 1; i < n; i++)
{
if (num[i] > v.back())
{
v.push_back(num[i]);
lis[i] = ++size;
}
else
{
int temp = lower_bound(v.begin(), v.end(), num[i]) - v.begin();
v[temp] = num[i];
lis[i] = temp + 1;
}
}

v.clear();
size = 1;
v.push_back(num[n - 1]);
lds[n - 1] = 1;
for (i = n - 2; i >= 0; i--)
{
if (num[i] > v.back())
{
v.push_back(num[i]);
lds[i] = ++size;
}
else
{
int temp = lower_bound(v.begin(), v.end(), num[i]) - v.begin();
v[temp] = num[i];
lds[i] = temp + 1;
}
}

/*for (i = 0; i < n; i++)
printf("%d ", lis[i]);
putchar('\n');
for (i = 0; i < n; i++)
printf("%d ", lds[i]);*/

int max = 0;
for (i = 0; i < n; i++)
{
int temp = min(lis[i], lds[i]);
if (max < temp)
max = temp;
}

printf("%d\n", max * 2 - 1);
}

return 0;
}