题意:
数组有序是指每一个数的上一位都不大于当前数,下一位都不小于当前数。如果数组不是有序的,那么需要在当前层次中找出导致不有序的数进行销毁,如当前序列为1,4,5,2,3,那么破坏有序的数有5和2。如果销毁之后的序列还是不有序的,重复该销毁操作。求最终的序列(n <= 1e5),T组数据(T <= 10)。
思路:
对于这题肯定不能暴力模拟,必定炸。然而怎么求呢,我们分析可知销毁当前这个数,只会影响它前面的一个数和后面一个数的关系,只有在它们之间导致再次出现破坏有序的情况。所以我们只需维护需要进行判断的几个数就行了,这样相当于一个大大的剪纸,而对于序列的改变,通过模拟链表进行改变就好了。
代码:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5+5;
vector<int> vt[2], ans;
int t, n, a[maxn];
bool mark[maxn];
int pre[maxn], nex[maxn];
void work()
{
int key = 0;
while(!vt[key].empty())
{
for(int i = 0; i < vt[key].size(); ++i)
{
int x = vt[key][i];
if((pre[x] == 0 || a[pre[x]] <= a[x]) &&
(nex[x] == n+1 || a[nex[x]] >= a[x])) continue;
mark[x] = 1;
}
for(int i = 0; i < vt[key].size(); ++i)
{
int x = vt[key][i];
if(!mark[x]) continue;
nex[pre[x]] = nex[x];
if(pre[x] != 0 && (vt[key^1].empty() || vt[key^1].back() != pre[x]))
{
vt[key^1].push_back(pre[x]);
}
nex[pre[x]] = nex[x];
if(nex[x] != n+1 && !mark[nex[x]])
{
vt[key^1].push_back(nex[x]);
}
pre[nex[x]] = pre[x];
mark[x] = 0;
}
vt[key].clear();
key ^= 1;
}
ans.clear();
int now = 0;
while(nex[now] != n+1)
{
ans.push_back(nex[now]);
now = nex[now];
}
printf("%d\n", ans.size());
for(int i = 0; i < ans.size(); ++i)
{
printf("%d ", a[ans[i]]);
}
printf("\n");
}
int main()
{
//freopen("in.txt", "r", stdin);
for(scanf("%d", &t); t--;)
{
scanf("%d", &n);
memset(mark, 0, sizeof mark);
vt[0].clear(); vt[1].clear();
for(int i = 1; i <= n; ++i)
{
scanf("%d", &a[i]);
vt[0].push_back(i);
pre[i] = i-1; nex[i] = i+1;
}
nex[0] = 1; pre[n+1] = n;
work();
}
return 0;
}
继续加油~