Cod sursa(job #533204)

Utilizator marcelcodreaCodrea Marcel marcelcodrea Data 13 februarie 2011 14:57:44
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.22 kb
#include<stdio.h>
#define N 200005
#define INF 1000000005
#define type HeapEl
struct HeapEl {
    int v;
    int nrIntrare;
};
int n;
type heap[N];
int nrEl;
int pozInHeap[N];
inline int st(int p) {return 2 * p;}
inline int dr(int p) {return 2 * p + 1;}
inline int pr(int p) {return p / 2;}
void swap(int l1,int l2) {
    int auxpoz  = pozInHeap[heap[l1].nrIntrare];
    pozInHeap[heap[l1].nrIntrare] =  pozInHeap[heap[l2].nrIntrare];
    pozInHeap[heap[l2].nrIntrare] = auxpoz;
    type aux = heap[l1];
    heap[l1] = heap[l2];
    heap[l2] = aux;

}
void up(int t) {

    while (t > 1 && heap[t].v < heap[pr(t)].v)  {
        swap(t,pr(t));
        t = pr(t);
    }
}
void down(int p) {
    int min = heap[p].v;
    int poz = p;
    if (dr(p) <= nrEl) {
        if (heap[st(p)].v < heap[dr(p)].v) {
            poz = st(p);
            min = heap[st(p)].v;
        }
        else {
            poz = dr(p);
            min = heap[dr(p)].v;
        }
        if (min > heap[p].v) {
            min = heap[p].v;
            poz = p;
        }
    }
    else
     if (st(p) <= nrEl) {
         if (heap[st(p)].v < min) {
            poz = st(p);
            min = heap[st(p)].v;
        }
     }
     if (poz != p) {
         swap(p,poz);
         down(poz);
     }
}
void insert(int e) {
    heap[++nrEl].v = e;
    heap[nrEl].nrIntrare = pozInHeap[0];
    up(nrEl);

}
void sterge(int e) {
    int aux = pozInHeap[e];
    swap(pozInHeap[e], nrEl);
    nrEl--;
    down(aux);
}
int getMin()  {
    int min = heap[1].v;
   /* heap[1] = heap[nrEl];
    pozInHeap[heap[nrEl].nrIntrare] = 1;
    nrEl--;
    down(1);*/
    return min;
}
int main() {
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);

    scanf("%d",&n);
    for(int i = 0; i < n; i++) {
        int cod;
        scanf("%d",&cod);
        if (cod == 1) {
            int x;
            scanf("%d",&x);
            pozInHeap[++pozInHeap[0]] = nrEl + 1;
            insert(x);
        }
        if (cod == 2) {
            int x;
            scanf("%d",&x);
            sterge(x);
        }
        if (cod == 3) {
            printf("%d\n",getMin());
        }
    }
    return 0;
}