Cod sursa(job #1494986)

Utilizator Burbon13Burbon13 Burbon13 Data 2 octombrie 2015 10:45:48
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
#include <cstdio>
#include <iostream>
#define nmx 200002
using namespace std;

int n,total,intrate,pos[nmx];
pair <int,int> h[nmx];

void perculate(const int nod) {
    if(nod > 1 && h[nod].first < h[nod/2].first) {
        swap(pos[h[nod].second],pos[h[nod/2].second]);
        swap(h[nod],h[nod/2]);
        perculate(nod/2);
    }
}

void sift(const int nod) {
    if(2*nod <= total) {
        if(2*nod+1 <= total && h[nod].first > h[2*nod+1].first && h[2*nod].first > h[2*nod+1].first) {
            swap(pos[h[nod].second],pos[h[2*nod+1].second]);
            swap(h[nod],h[2*nod+1]);
            sift(2*nod+1);
        }
        else if(h[nod].first > h[2*nod].first){
            swap(pos[h[nod].second],pos[h[2*nod].second]);
            swap(h[nod],h[2*nod]);
            sift(2*nod);
        }
    }
}

int main() {
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);

    scanf("%d", &n);
    int cond,nr;
    for(int i = 1; i <= n; ++i) {
        scanf("%d", &cond);
        if(cond == 1) {
            scanf("%d", &nr);
            h[++total].first = nr;
            pos[++intrate] = total;
            h[total].second = intrate;
            perculate(total);
            continue;
        }
        if(cond == 2) {
            scanf("%d", &nr);
            int p = pos[nr];
            swap(pos[nr],pos[h[total].second]);
            h[p] = h[total--];
            if(p > 1 && h[p].first < h[p/2].first)
                perculate(p);
            else
                sift(p);
            continue;
        }
        printf("%d\n", h[1].first);
    }

    return 0;
}