Cod sursa(job #1652787)

Utilizator andytosaAndrei Tosa andytosa Data 15 martie 2016 14:01:05
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.98 kb
#include <fstream>

using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

int heap[2000010], n, c, x, k, ord[2000010], poz;

int father(int nod){ return nod / 2; }
int left_son(int nod){ return nod * 2; }
int right_son(int nod){ return nod * 2 + 1; }

void percolate(int nod){
    while(nod > 1 && heap[nod] < heap[ father(nod) ]){
        swap(heap[nod], heap[ father(nod) ]);
        swap(ord[nod], ord[ father(nod) ]);
        nod = father(nod);
    }
}

void sift(int nod){
    int son;
    do{
        son = 0;
        if(left_son(nod) <= n){
            son = left_son(nod);
            if(right_son(nod) <= n && heap[right_son(nod)] < heap[left_son(nod)])
                son = right_son(nod);
            if(heap[son] <= heap[nod])
                son = 0;
        }
        if(son){
            swap(heap[nod], heap[son]);
            swap(ord[nod], ord[son]);
            nod = son;
        }
    }while(son);
}

int main()
{
    fin >> k;
    for(int i = 1; i <= k; ++i){
        fin >> c;
        if(c == 3){
            //fout << '\n';
            fout << heap[1] << '\n';
            //fout << '\n';
        }
        else {
            fin >> x;
            if(c == 1){
                heap[++n] = x;
                ord[n] = ++poz;
                percolate(n);
            }
            else {
                for(int i = 1; i <= n; ++i)
                    if(x == ord[i]){
                        x = i;
                        break;
                    }

                heap[x] = heap[n--];
                if(n > 1 && heap[father(x)] < heap[x])
                    percolate(x);
                else
                    sift(x);
            }
            //for(int i = 1; i <= n; ++i)
             //   fout << heap[i] << ' ';
            //fout << '\n';
            //for(int i = 1; i <= n; ++i)
            //    fout << ord[i] << ' ';
            //fout << '\n';
        }
    }
    return 0;
}