Cod sursa(job #1770412)

Utilizator VladTiberiuMihailescu Vlad Tiberiu VladTiberiu Data 4 octombrie 2016 11:26:54
Problema Sortare prin comparare Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.26 kb
#include <bits/stdc++.h>

#define NMax 500010
using namespace std;
ifstream f("algsort.in");
ofstream g("algsort.out");

int n,p,x,nr;
int H[NMax],node[NMax],order[NMax],a[NMax];

void add(int x,int &n){
    H[n] = x;
    n++;
    int i = n - 1;
    while(H[(i - 1) / 2] > H[i] && i > 0){
        swap(H[(i - 1) / 2], H[i]);

        node[order[i]] = (i - 1) / 2;
        node[order[(i - 1) / 2]] = i;
        swap(order[i],order[(i - 1) / 2]);

        i = (i - 1) / 2;
    }
}
void del(int x,int &n){
    swap(H[x],H[n - 1]);
    n--;
    int i = x;
    while(i < n){
        int son = -1;
        if(H[2 * i + 1] < H[i] && 2 * i + 1 < n){
            son = 2 * i + 1;
        }
        if(H[2 * i + 2] < H[i] && 2 * i + 2 < n){
            if(son == -1)
                son = 2 * i + 2;
            else
                if(H[2 * i + 2] < H[2 * i + 1])
                    son = 2 * i + 2;
        }
        if(son == -1)
            break;
        swap(H[i], H[son]);

        node[order[i]] = son;
        node[order[son]] = i;
        swap(order[i],order[son]);

        i = son;
    }
}
int main()
{
    f >> n;
    int nr = 0;
    for(int i = 0; i < n; ++i){
        f >> a[i];
        add(a[i],nr);
    }
    while(nr){
        g << H[0] << ' ';
        del(0,nr);
    }
    return 0;
}