1. 程式人生 > >Brute Force Sorting HDU

Brute Force Sorting HDU

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;
}