题目链接;
题意:给出一个序列,从左到右扫一遍,每个数如果比左面相邻的小或者比右边相邻的大,就删掉,先不更新,最后扫过一遍统一更新,更新完后的序列重复操作,直至满足没有可以删除的项。
思路:
最开始想着维护一个K值(当前队列的顶端值),一遍扫过出答案,wa了。
根据题目模拟去写一遍一遍的去扫序列,用双端链表去更新序列,更新后重复操作,最后输出链表上的值。
#include <cstdio>
#include <cstring>
#define MAXN 100010
int a[MAXN], que[MAXN], next[MAXN], last[MAXN];
int main() {
int t, n;
scanf("%d", &t);
while(t--) {
scanf("%d", &n);
for(int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
last[i] = i - 1; //数组模拟链表
next[i] = i + 1;
que[i - 1] = i;
}
last[n] = n + 1, next[0] = 1;
int top = n, ans = n;
bool flag = true;
while(flag) { //多次遍历更新的序列,直到不可删除
flag = false;
int now = 0, s = 0;
while(now < top) { //遍历序列
int i = que[now], res = 0;
while(next[i] <= n && a[i] > a[next[i]]) {
res++;
i = next[i];
flag = true;
}
if(res) { //更新序列,重点
ans -= res + 1;
next[last[que[now]]] = next[i];
last[next[i]] = last[que[now]];
que[s++] = last[que[now]];
}
while(que[now] <= i && now < top) now++;
}
top = s; //新序列的个数
}
int now = 0;
printf("%d\n", ans);
while(now <= n) {
if(now != 0) printf("%d ", a[now]);
now = next[now];
}
printf("\n");
}
return 0;
}