Cod sursa(job #704527)

Utilizator xulescuStefu Gabriel xulescu Data 2 martie 2012 18:33:56
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include <fstream>

#define MAXN 200001
using namespace std;

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

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(heap[poz]<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(heap[f1]<heap[poz]) min=f1;
    if(f2<=dim) if(heap[f2]<heap[min]) min=f2;
    if(min!=poz){
        swap(heap[min],heap[poz]);
        downheap(min);
    }
}

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

void del(int val){
    for(int i=1;i<=n;i++)
        if(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 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<<heap[1]<<"\n"; continue; }
        f >> b;
        if(a==1) insert(b);
        else if(a==2) del(hist[b]);
    }
    f.close();
    g.close();

    return 0;
}