Cod sursa(job #705157)

Utilizator xulescuStefu Gabriel xulescu Data 3 martie 2012 14:57:01
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
#include <fstream>

#define MAXN 200001
using namespace std;

int n;
int k, hist[MAXN];
int heap[MAXN], dim;
int pozh[MAXN];

void swap(int &a, int &b){ int c = a; a=b; b=c; }

void upheap(int poz){
    if(poz==1) return;
    int p = poz/2;
    if(hist[heap[poz]]<hist[heap[p]]){
        swap(pozh[heap[poz]],pozh[heap[p]]);
        swap(heap[poz],heap[p]);
        upheap(p);
    }
}

void downheap(int poz){
    int f1 = poz*2;
    int f2 = poz*2+1;
    int min = poz;
    if(f1<=dim) if(hist[heap[f1]]<hist[heap[poz]]) min=f1;
    if(f2<=dim) if(hist[heap[f2]]<hist[heap[min]]) min=f2;
    if(min!=poz){
        swap(pozh[heap[min]],pozh[heap[poz]]);
        swap(heap[min],heap[poz]);
        downheap(min);
    }
}

void insert(int val){
    hist[++k]=val;
    heap[++dim]=k;
    pozh[k]=dim;
    upheap(dim);
}

void del(int b){
    //for(int i=1;i<=n;i++)
        /*if(hist[heap[i]]==val){
            swap(heap[i],heap[dim]);
            dim--;
            int p = i/2;
            if(p && heap[p]>heap[i]){ upheap(i); return; }
            downheap(i);
            break;
        }*/
    int last = heap[dim];
    int pozb = pozh[b];
    swap(heap[pozh[b]],heap[dim]);
    pozh[last]=pozh[b];
    pozh[b]=0;
    dim--;
    int p = pozb/2;
    if(p && hist[heap[p]]>hist[heap[pozb]]){ upheap(pozb); return; }
    downheap(pozb);

}

int main(){
    ifstream f("heapuri.in");
    ofstream g("heapuri.out");
    f >> n;
    int a,b;
    for(int i=0;i<n;i++){
        f >> a;
        if(a==3){ g<<hist[heap[1]]<<"\n"; continue; }
        f >> b;
        if(a==1) insert(b);
        else if(a==2) del(b);
    }
    f.close();
    g.close();

    return 0;
}