Description
给出一个长度为 n n 序列,每步操作会把该序列中无序元素全部删除,直至没有无序元素为止,一个元素 a[i] a [ i ] 是有序的当且仅当其满足以下条件
1. a[i] a [ i ] 是当前序列的第一个元素或 a[i]≥a[i−1] a [ i ] ≥ a [ i − 1 ]
2. a[i] a [ i ] 是当前序列的最后一个元素或 a[i]≤a[i+1] a [ i ] ≤ a [ i + 1 ]
问操作后的序列
Input
第一行一整数 T T 表示用例组数,每组用例首先输入一整数表示序列长度,之后输入 n n 个整数表示该序列 (1≤T≤100,1≤n≤105,1≤a[i]≤105) ( 1 ≤ T ≤ 100 , 1 ≤ n ≤ 10 5 , 1 ≤ a [ i ] ≤ 10 5 )
Output
输出操作后的序列长度和序列
Sample Input
5
5
1 2 3 4 5
5
5 4 3 2 1
5
1 2 3 2 1
5
1 3 5 4 2
5
2 4 1 3 5
Sample Output
5
1 2 3 4 5
0
2
1 2
2
1 3
3
2 3 5
Solution
当前序列无序元素必然与上一次操作时某个无序元素相邻,用链表维护元素的邻接关系,用队列维护无序元素,开一个标记数组标记一个元素是否被删除,每次删去一个无序元素就通过链表找其前驱后继判断其是否成为新的无序元素,如果是则加入到队列中,同时注意修改删去元素前驱后继的前驱后继值,直至队列为空即表示序列整体有序
Code
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int INF=0x3f3f3f3f,maxn=100005;
int T,n,a[maxn],L[maxn],R[maxn],vis[maxn];
queue<int>que;
int main()
{
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
for(int i=1;i<=n;i++)scanf("%d",&a[i]);
if(n==1)
{
printf("1\n%d\n",a[1]);
continue;
}
a[n+1]=INF;
for(int i=1;i<=n;i++)
{
L[i]=i-1,R[i]=i+1,vis[i]=0;
if(a[i]<a[i-1]||a[i]>a[i+1])que.push(i),vis[i]=1;
}
while(!que.empty())
{
int x=que.front();que.pop();
int l=L[x],r=R[x];
L[r]=l,R[l]=r;
if(l!=0&&r!=n+1&&!vis[r]&&a[l]>a[r])
{
que.push(l),vis[l]=1;
que.push(r),vis[r]=1;
}
}
int res=0;
for(int i=1;i<=n;i++)
if(!vis[i])a[++res]=a[i];
printf("%d\n",res);
for(int i=1;i<=res;i++)printf("%d ",a[i]);
printf("\n");
}
return 0;
}