Cod sursa(job #1904786)

Utilizator roxanastRoxana Stiuca roxanast Data 5 martie 2017 19:39:41
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include <fstream>
#define NMAX 200010
using namespace std;

ifstream f("heapuri.in");
ofstream g("heapuri.out");


int n,i,cnth,cnt,poz[NMAX];
struct heap{
int val,ind;
}h[NMAX];
void up(int p){
    if(p>1&&h[p].val<h[p/2].val){
        swap(h[p],h[p/2]);
        swap(poz[h[p].ind],poz[h[p/2].ind]);
        up(p/2);
    }
}
void down(int p){
    if(2*p<=cnth){
        int x=p;
        if(h[2*p].val<h[x].val)
            x=2*p;
        if(2*p+1<=cnth&&h[2*p+1].val<h[x].val)
            x=2*p+1;
        if(x!=p){
            swap(h[p],h[x]);
            swap(poz[h[x].ind],poz[h[p].ind]);
            down(x);
        }
    }
}
void scot(int p){
    //poz[p]
    h[poz[p]]=h[cnth];
    poz[h[cnth].ind]=poz[p];
    cnth--;
    up(poz[p]);
    down(poz[p]);

}
void adaug(int p){
    h[++cnth].val=p;
    h[cnth].ind=cnt;
    poz[cnt]=cnth;
    up(cnth);
}
int main()
{
    f>>n;
    cnt=0;
    for(i=1;i<=n;i++){
        int op,x;
        f>>op;
        if(op==1){
           f>>x;
           cnt++;
           adaug(x);
        }
        if(op==2){
            f>>x;
            scot(x);
        }
        if(op==3){
            g<<h[1].val<<'\n';
        }
    }
    return 0;
}