Cod sursa(job #2013373)

Utilizator valorosu_300Cristian Gherman valorosu_300 Data 21 august 2017 10:49:28
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <fstream>
using namespace std;
ifstream in("heapuri.in");
ofstream out("heapuri.out");
const int N = 200005;
int h[N],ord[N],poz[N];
void up_heap(int f){
    while(f/2 && h[ord[f]] < h[ord[f/2]]){
        swap(ord[f],ord[f/2]);
        poz[ord[f]] = f;
        poz[ord[f/2]] = f/2;
        f /= 2;
    }
}
void down_heap(int t, int l){
    int f = 0;
    while(t != f){
        f = t;
        if(f*2 <= l && h[ord[t]] > h[ord[f*2]])
            t = f*2;
        if(f*2 + 1 <= l && h[ord[t]] > h[ord[f*2+1]])
            t = f*2+1;
        swap(ord[t],ord[f]);
        poz[ord[t]] = t;
        poz[ord[f]] = f;
    }
}
void insert_heap(int x, int &nr, int &l){
    h[++nr] = x;
    ord[++l] = nr;
    poz[nr] = l;
    up_heap(l);
}
void make_top(int x){
    ///elem de pe poz x devine vf
    h[x] = -1;
    up_heap(poz[x]);
}
void remove_top(int &l){
    poz[ord[1]] = 0;
    ord[1] = ord[l--];
    poz[ord[1]] = 1;
    down_heap(1,l);
}
void print_top(){
    out<<h[ord[1]]<<"\n";
}
int main()
{
    int n,op,l = 0,nr = 0,x;
    in>>n;
    for(int i=1;i<=n;i++){
        in>>op;
        if(op == 1){
            in>>x;
            insert_heap(x,nr,l);
        }
        else if(op == 2){
            in>>x;
            make_top(x);
            remove_top(l);
        }
        else if(op == 3)
            print_top();
    }
    in.close();
    out.close();
    return 0;
}