0%

CF2001D Longest Max Min Subsequence

Problem - 2001D - Codeforces

Solution

所求序列长度为 aa 中的元素种类数。小根堆 LL 维护每种元素最后一次出现的位置

第一步,开大根堆 DD 和小根堆 UU,把位置 1Ltop1\sim L_{top} 的元素同时放进 DDUU 中。由于答案序列的第一位是负数,所以要取 DD 的堆顶作为答案序列的第一位。然后标记该数字已使用。后续使用 UUDDLL 时,将与该数字相关或出现位置在它之前的成员从堆中弹出。

后续同理,可逐位构造出答案序列。

时间复杂度 O(nlogn)O(n\log n)

Code

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 <bits/stdc++.h>
using namespace std;

const int N = 3e5 + 10;

int T, n, a[N], loc[N], used[N], tot, ans[N], cnt, tag;
struct Node {
int x, y;
friend bool operator > (const Node &a, const Node &b) {
if (a.x == b.x)
return a.y < b.y;
return a.x > b.x;
}
friend bool operator < (const Node &a, const Node &b) {
if (a.x == b.x)
return a.y > b.y;
return a.x < b.x;
}
};
priority_queue<Node> down;
priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > lst, up;

void solve()
{
scanf("%d", &n);
cnt = tot = tag = 0;
while (down.size()) down.pop();
while (up.size()) up.pop();
while (lst.size()) lst.pop();
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
loc[a[i]] = i;
used[i] = 0;
}
for (int i = 1; i <= n; i++)
if (loc[a[i]] == i)
lst.push({i, a[i]}), tot++;
int p = 0;
while (tot--) {
while (used[lst.top().second])
lst.pop();
while (p < lst.top().first) {
p++;
up.push({a[p], p});
down.push({a[p], p});
}
++cnt;
if (cnt & 1) {
while (used[down.top().x] || down.top().y <= tag)
down.pop();
ans[cnt] = down.top().x;
tag = down.top().y;
} else {
while (used[up.top().first] || up.top().second <= tag)
up.pop();
ans[cnt] = up.top().first;
tag = up.top().second;
}
used[ans[cnt]] = 1;
}
printf("%d\n", cnt);
for (int i = 1; i <= cnt; i++)
printf("%d ", ans[i]);
putchar('\n');
}

int main()
{
scanf("%d", &T);
while (T--) solve();
return 0;
}