Cod sursa(job #1160737)

Utilizator florin.ilieFlorin Ilie florin.ilie Data 30 martie 2014 19:11:19
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.59 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

int n,k,l,com,num;
vector <int> heap;
int sir[200010];
int poz[200010];

void inter (int x,int y){
    int t=heap[x];
    heap[x]=heap[y];
    heap[y]=t;
}

void upheap (int what){
    int tata;
    while(what>1){
        tata = what>>1;
        if(sir[heap[tata]]>sir[heap[what]]){
            poz[heap[what]]=tata;
            poz[heap[tata]]=what;
            inter(tata,what);
            what=tata;
        }
        else what=1;
    }
}

void downheap (int what)
{
    int f;
    while(what<=k){
        if(what<<1<=k){
            f=what<<1;
            if(f+1<=k){
                if(sir[heap[f+1]]<sir[heap[f]])
                    f++;
            }
        }
        else return;
        if(sir[heap[what]]>sir[heap[f]])
        {
            poz[heap[what]]=f;
            poz[heap[f]]=what;
            inter(what,f);
            what = f;
        }
        else return;
    }

}

int main()
{
    ifstream fin("heapuri.in");
    ofstream fout("heapuri.out");
    heap.push_back(0);
    fin>>n;
    for(;n>0;n--){
        fin>>com;
        switch(com){
            case 1:
                fin>>sir[++l];
                heap.push_back(l);
                poz[l]=++k;
                upheap(k);
                break;
            case 2:
                fin>>num;
                sir[num]=1000000001;
                downheap(poz[num]);
                heap.pop_back();
                k--;
                break;
            case 3:
                fout<<sir[heap[1]]<<'\n';
                break;
        }
    }
    return 0;
}