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
Sample Output
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[n]) ==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
****************************************************************/
本文探讨了如何利用已排序子序列的特性来解决一个部分排序序列的问题。通过分析并组合不同子序列的排序特点,实现整个序列从最小到最大的排序。重点介绍了输入与输出规范,以及一种高效的算法实现方式,包括使用堆数据结构进行排序。实例展示了算法在具体场景中的应用,特别强调了性能优化技巧。

被折叠的 条评论
为什么被折叠?



