Cod sursa(job #1493264)

Utilizator Burbon13Burbon13 Burbon13 Data 28 septembrie 2015 22:10:57
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include <cstdio>
#include <iostream>
#define nmx 300003
using namespace std;

int n, loc[nmx], t;
pair <int,int> h[nmx];

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

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

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

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

    }


    return 0;
}