Cod sursa(job #1108740)

Utilizator apopeid14Apopei Daniel apopeid14 Data 16 februarie 2014 10:47:08
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include <cstdio>
#include <algorithm>
#define MAX 200001
 
int N, T, C;
int heap[MAX], pos[MAX], tim[MAX];
 
void add();
void del();
 
int main()
{
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);
 
    scanf("%d", &N);
    for (int i=1; i<=N; ++i){
        int op;
 
        scanf("%d", &op);
        switch (op){
            case 1:
                add();
                break;
            case 2:
                del();
                break;
            case 3:
                printf("%d\n", heap[1]);
                break;
        }
    }
    return 0;
}
 
void add(){
    int x, p=++C;
 
    ++T;
    scanf("%d", &x);
    heap[p] = x;
    pos[T] = p;
    tim[p] = T;
 
    while (p>1 && heap[p]<heap[p/2]){
        std::swap(heap[p], heap[p/2]);
        std::swap(pos[tim[p]], pos[tim[p/2]]);
        std::swap(tim[p], tim[p/2]);
        p = p/2;
    }
}
 
void del(){
    int t, p;
 
    scanf("%d", &t);
    p = pos[t];
 
    heap[p] = heap[C];
    tim[p] = tim[C];
    pos[tim[p]] = p;
 
    pos[t] = 0;
    --C;
    for (bool finish=0; !finish; ){
        finish = 1;
        if (2*p <= C){
            int minim = 2*p;
 
            if (2*p+1 <= C){
                if (heap[2*p+1] < heap[minim])
                    minim = 2*p+1;
            }
 
            if (heap[minim] < heap[p]){
                finish = 0;
                std::swap(heap[p], heap[minim]);
                std::swap(pos[tim[p]], pos[tim[minim]]);
                std::swap(tim[p], tim[minim]);
                p = minim;
            }
        }
    }
}