您的位置:首页 > 其它

Combining sorting methold

2016-05-11 17:46 176 查看

Description

Everybody with computer science background more or less has learnt something about sorting methods such as selection sort, insertion sort, merge sort and quick sort. It is with sheer significance that we could use these sort methods
flexibility and combine their respective characteristics to solve some new problems. Now, there is a sequence of numbers having been sorted partially. Here, partially sorted means the sequence is combined by several subsequences which have been sorted from
smallest to largest. For example, the given sequence is 7 8 9 1 2 11 39 9 9 which is composed by sorted subsequences 7 8 9, 1 2 11 39, 9 9.  Your task is to sort the given sequence from smallest to largest using characterizes of the sorted subsequences. 

Input

A given sequence described above whose length is no longer than 3,000,000. The absolute values of the numbers of the sequence are no larger than 2^31. (Obviously we do not want you to directly use the sort methods you have learnt
before and such directly use will probably causeruntime error). 

Output

Sorted sequence of the given sequence.

Sample Input

7 8 9 1 11 2

Sample Output

1 2 7 8 9 11

HINT

We stongly suggest you to using scanf and printf to input and output in order to saving time.

#include <cstdio>

using namespace std;

const int maxn = 3000100;

struct heap {
int key, NO;
};

int n, m, a[maxn], P[maxn], L[maxn], R[maxn];
heap T[maxn];

void Input() {
n = 1;
while (scanf("%d", &a
) ==1)
n++;
n--;

m = 1; L[1] = 1; P[1] = 1;
for (int i = 2; i <= n; i++)
if (a[i - 1] > a[i]) {
R[m] = i - 1;
m++; L[m] = i;
}
R[m] = n;
}

void Swap(int i, int j) {
heap tmp;
tmp = T[i]; T[i] = T[j]; T[j] = tmp;
}

void MinHeap(int i) {
int j = i;
if (i * 2 <= m && T[i].key > T[i * 2].key) j = i * 2;
if (i * 2 + 1 <= m && T[j].key > T[i * 2 + 1].key) j = i * 2 + 1;
if (j != i) {
Swap(i, j);
MinHeap(j);
}
}

void Build() {
for (int i = 1; i <= m; i++) {
T[i].key = a[L[i]];
T[i].NO = i;
P[i] = L[i];
}
for (int i = m / 2; i >= 1; i--)
MinHeap(i);
}

int main() {
Input();

Build();
for (int i = 1; i <= n; i++) {
printf("%d", T[1].key);
if (i != n) printf(" "); else { printf("\n"); break; };

int j = T[1].NO;
if (P[j] != R[j]) {
P[j]++; T[1].key = a[P[j]];
}
else {
T[1] = T[m];
m--;
}
MinHeap(1);
}

return 0;
}
/**************************************************************
Problem: 1158
User: 141220110
Language: C++
Result: Accepted
Time:1116 ms
Memory:71132 kb
****************************************************************/


4000
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: