Cod sursa(job #1493160)

Utilizator Burbon13Burbon13 Burbon13 Data 28 septembrie 2015 19:56:06
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 kb
#include <cstdio>
#include <iostream>
#define nmx 200003
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){
        int fiu = h[pos*2].first;
        if(pos*2+1 <= t && h[pos].first > fiu && 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];
            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;
}