Cod sursa(job #1770407)

Utilizator VladTiberiuMihailescu Vlad Tiberiu VladTiberiu Data 4 octombrie 2016 11:18:24
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <bits/stdc++.h>

#define NMax 200010
using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");

int n,p,x,nr;
int H[NMax],node[NMax],order[NMax];

void add(int x,int &n){
    H[n] = x;
    n++;
    int i = n - 1;
    while(H[(i - 1) / 2] > H[i] && i > 0){
        swap(H[(i - 1) / 2], H[i]);

        node[order[i]] = (i - 1) / 2;
        node[order[(i - 1) / 2]] = i;
        swap(order[i],order[(i - 1) / 2]);

        i = (i - 1) / 2;
    }
}
void del(int x,int &n){
    swap(H[x],H[n - 1]);
    n--;
    int i = x;
    while(i < n){
        int son = -1;
        if(H[2 * i + 1] < H[i] && 2 * i + 1 < n){
            son = 2 * i + 1;
        }
        if(H[2 * i + 2] < H[i] && 2 * i + 2 < n){
            if(son == -1)
                son = 2 * i + 2;
            else
                if(H[2 * i + 2] < H[2 * i + 1])
                    son = 2 * i + 2;
        }
        if(son == -1)
            break;
        swap(H[i], H[son]);

        node[order[i]] = son;
        node[order[son]] = i;
        swap(order[i],order[son]);

        i = son;
    }
}
int main()
{
    int t;
    f >> t;
    for(int i = 1; i <= t; ++i){
        f >> p;
        if(p == 1){
            f >> x;

            node[nr] = n;
            order[n] = nr;
            ++nr;

            add(x,n);
        }
        if(p == 2){
            f >> x;
            del(node[x - 1],n);
        }
        if(p == 3){
            g << H[0] << '\n';
        }
    }
    return 0;
}