Cod sursa(job #1741109)

Utilizator MiricaMateiMirica Matei MiricaMatei Data 12 august 2016 23:28:52
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.08 kb
#include <cstdio>
#include <algorithm>
using namespace std;
const int MAX_SIZE = 200000;
const int INF = 999999999;
int heap[MAX_SIZE + 5];
int poz[MAX_SIZE + 5], v[MAX_SIZE + 5], f[MAX_SIZE + 5], intr;
int father(int nod){
    return nod / 2;
}
int left_son(int nod){
    return 2 * nod;
}
int right_son(int nod){
    return 2 * nod + 1;
}
int minim(){
    return heap[1];
}
void sift(int n, int k){
    int son;
    do{
        son = 0;
        if (left_son(k) <= n){
            son = left_son(k);
            if (right_son(k) <= n && heap[right_son(k)] < heap[left_son(k)])
                son = right_son(k);
            if (heap[k] <= heap[son])
                son = 0;
        }
        if (son){
            swap(poz[k], poz[son]);
            f[poz[k]] = k;
            f[poz[son]] = son;
            swap(heap[k], heap[son]);
            k = son;
        }
    }while(son);
}
void percolate(int n, int k){
    int p = heap[k];
    while (k > 1 && p < heap[father(k)]){
        heap[k] = heap[father(k)];
        swap(poz[k], poz[father(k)]);
        f[poz[k]] = k;
        f[poz[father(k)]] = father(k);
        k = father(k);
    }
    heap[k] = p;
}
void cut(int &n, int k){
    poz[n] = poz[k];
    heap[k] = heap[n];
    n --;
    if (k > 1 && heap[k] < heap[father(k)])
        percolate(n, k);
    else
        sift(n, k);
}
void insert(int &n, int k){
    v[++intr] = k;
    n ++;
    poz[n] = intr;
    f[intr] = n;
    heap[n] = k;
    percolate(n, n);
}
int main(){
    freopen("heapuri.in", "r",  stdin);
    freopen("heapuri.out", "w",  stdout);
    int n, m, i, op, val;
    char c;
    n = 0;
    scanf("%d", &m);
    for (i = 1; i <= MAX_SIZE; i ++)
        heap[i] = INF;
    for (i = 1; i <= m; i ++){
        scanf("%d", &op);
        c = getc(stdin);
        if (c == '\n' || c == EOF)
            printf("%d\n", minim());
        else{
            scanf("%d", &val);
            if (op == 1)
                insert(n, val);
            else
                cut(n, f[val]);
        }
    }
    return 0;
}