Brute Force Sorting HDU - 6215

版权声明:小白一个,欢迎各位指错。 https://blog.csdn.net/qq_36424540/article/details/82701227

Beerus needs to sort an array of N integers. Algorithms are not Beerus's strength. Destruction is what he excels. He can destroy all unsorted numbers in the array simultaneously. A number A[i] of the array is sorted if it satisfies the following requirements.
1. A[i] is the first element of the array, or it is no smaller than the left one A[i−1].
2. A[i] is the last element of the array, or it is no bigger than the right one A[i+1].
In [1,4,5,2,3], for instance, the element 5 and the element 2 would be destoryed by Beerus. The array would become [1,4,3]

. If the new array were still unsorted, Beerus would do it again.
Help Beerus predict the final array.

Input

The first line of input contains an integer T (1≤T≤10)

which is the total number of test cases.
For each test case, the first line provides the size of the inital array which would be positive and no bigger than 100000.
The second line describes the array with N positive integers A[1],A[2],⋯,A[N] where each integer A[i] satisfies 1≤A[i]≤100000

.

Output

For eact test case output two lines.
The first line contains an integer M

which is the size of the final array.
The second line contains M integers describing the final array.
If the final array is empty, M should be 0

and the second line should be an empty line.

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 
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;

#define rep(i,a,b) for(int i=a;i<b;++i)
#define per(i,a,b) for(int i=b-1;i>=a;--i)

const int N=2e5+10;

int q[N],head,tail;

int val[N],pre[N],nxt[N];

/*
当时写了双向链表,但是后来也明白了 可能出现 一个一个的山峰,这样就会很耗时间,
所以想能不能处理出来,一个一个上升的段,但是处理恐怕极其麻烦。
还是左闭右开的思想,我们只保留一边。而且只保留可能出现下降点的位置,这样我们就可以 枚举这些有效的点。

不断地更新,但是有顺序,或者说是一段一段的迁移,我们应该考虑一下队列 
*/
int main() {
	int T;
	scanf("%d",&T);
	//read(T);
	while(T--) {
		//初始化队列
		head=tail=0;

		int n;
		scanf("%d",&n);
		//read(n);
		rep(i,1,n+1) {
			scanf("%d",&val[i]);
			//read(val[i]);
			pre[i]=i-1;
			nxt[i]=i+1;
			q[head++]=i;
		}
		pre[n+1]=n;  pre[0]=-1;
		nxt[n+1]=n+2;nxt[0]=1;
		
		int flag=1,num=0;
		int top=head;
		while(flag){
			flag=0,head=tail=0;
			while(tail<top) {
				int p=q[tail];
				while(nxt[p]<=n&&val[p]>val[nxt[p]]){
					flag=1;num++;
					p=nxt[p];
				}
				//	printf("tail:%d top:%d\n",tail,top);
				if(p!=q[tail]) {
					num++;
					nxt[pre[q[tail]]]=nxt[p];
					pre[nxt[p]]=pre[q[tail]];
				    if(pre[q[tail]]>0)q[head++]=pre[q[tail]];
				}
				while(tail<top&&q[tail]<=p)tail++;
			}
			if(!flag)break;
			top=head;
		}
		printf("%d\n",n-num);
		flag=0;
		for(int i=nxt[0]; i!=n+1; i=nxt[i]) {
			//printf("i:%d \n",i);
			 printf("%d ",val[i]);
		}
		printf("\n");
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36424540/article/details/82701227