HDU 6215 Brute Force Sorting(雙向連結串列+佇列)
Brute Force Sorting
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others) Total Submission(s): 2304 Accepted Submission(s): 539 Problem Description
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
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
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
Source
刪除陣列中的降序序列,形成一個新陣列,在刪除新陣列中的降序序列,直至陣列中不存在降序序列,每次只從開頭遍歷尋找降序序列肯定會T,我們可以用一個雙向連結串列來模擬整個過程,用一個佇列儲存有可能產生降序序列的頭節點(開始把所有節點都加進去),從佇列裡取出一個節點,判斷它後面的序列是否為降序,是則把這一段序列刪除,用雙向連結串列維護就行了,同時把頭節點的上一個節點加入佇列,直到某一次陣列不存在降序序列退出
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100005;
int que[MAXN],last[MAXN],Next[MAXN],a[MAXN];
int main(void)
{
int T,n,top;
scanf("%d",&T);
while(T--) {
top = 0;
scanf("%d",&n);
for(int i = 1; i <= n; i++) {
last[i] = i - 1;
Next[i] = i + 1;
scanf("%d",&a[i]);
que[top++] = i;
}
Next[0] = 1;
int ans = n,flag = 0;
while(1) {
int cnt = 0,cur = 0,flag = 0;
while(cur < top) {
int p = que[cur],num = 0;
while(Next[p] <= n && a[p] > a[Next[p]]) {
flag = 1;
num++;
p = Next[p];
}
if(num) {
ans -= (num + 1);
Next[last[que[cur]]] = Next[p];
last[Next[p]] = last[que[cur]];
que[cnt++] = last[que[cur]];
}
while(que[cur] <= p && cur < top) cur++;
}
top = cnt;
if(!flag) break;
}
printf("%d\n",ans);
int cur = 0;
while(cur <= n) {
if(cur) printf("%d ",a[cur]);
cur = Next[cur];
}
printf("\n");
}
return 0;
}