Cod sursa(job #2094031)

Utilizator sandupetrascoPetrasco Sandu sandupetrasco Data 24 decembrie 2017 21:09:00
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
#include <bits/stdc++.h>

#define pb push_back 
#define x first 
#define y second 
#define MOD 1000000007

using namespace std;
typedef long long ll;
typedef pair< int , int > PII;
const int dirx[] = {-2,-1,1,2, 1, -1};
const int diry[] = {0,1,1,0, -1, -1};
inline void debugMode() {
    #ifndef ONLINE_JUDGE
    freopen("algsort.in", "r", stdin);
    freopen("algsort.out", "w", stdout);
    #endif
}

int n, m, Heap[500100];

void down(int n, int p){
	int son;
	do{
		son = (p << 1) * (p << 1 <= n) + ((p << 1 | 1) <= n && Heap[p << 1 | 1] > Heap[p << 1]);
		son = (Heap[son] <= Heap[p] ? 0 : son);
		if (son){
			swap(Heap[son], Heap[p]);
			p = son;
		}

	} while (son);
}

void build(int p){
	for (int i = p / 2; i; i--){
		down(p, i);
	}
}

void insert(int val){
	Heap[n] = val;
}

void change_head(int n){
	swap(Heap[1], Heap[n]);
	down(n - 1, 1);
}

int main(){
	debugMode();
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	cin >> m;
	for (int i = 1, x; i <= m; i++){
		++n;
		cin >> x;
		insert(x);
	}
	
	build(n);

	for (int i = m; i >= 2; i--){
		change_head(i);
	}

	for (int i = 1; i <= n; i++) cout << Heap[i] << " ";

	return 0;
}