Cod sursa(job #2228569)

Utilizator FunnyStockyMihnea Andreescu FunnyStocky Data 4 august 2018 11:43:02
Problema Heapuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 2.3 kb
#include <iostream>
#include <cstdio>

using namespace std;

class heap {
    private :
        int v[200000+5];
        int where[200000+5];
        int ind[200000+5];
        int len=0;
        int cur=0;
    public :
        int get_min() {
            return v[1];
        }
        void in(int x) {
            v[++len]=x;
            where[++cur]=len;
            ind[len]=cur;
            int poz=len;
            while(poz>1 && v[poz/2]>v[poz]) {
                swap(v[poz/2],v[poz]);
                swap(ind[poz/2],ind[poz]);
                where[ind[poz/2]]=poz/2;
                where[ind[poz]]=poz;
                poz/=2;
            }
        }
        void out(int poz) {
            poz=where[poz];
            swap(v[poz],v[len]);
            swap(ind[poz],ind[len]);
            where[ind[poz]]=poz;
            where[ind[len]]=len;
            len--;
            poz=1;
            while(1) {
                int mi=v[poz];
                if(2*poz<=len) {
                    mi=min(mi,v[2*poz]);
                }
                if(2*poz+1<=len) {
                    mi=min(mi,v[2*poz+1]);
                }
                if(v[poz]==mi) {
                    break;
                }
                if(mi==v[2*poz]) {
                    swap(v[poz],v[2*poz]);
                    swap(ind[poz],ind[2*poz]);
                    where[ind[poz]]=poz;
                    where[ind[2*poz]]=2*poz;
                    poz=2*poz;
                }
                else {
                    swap(v[poz],v[2*poz+1]);
                    swap(ind[poz],ind[2*poz+1]);
                    where[ind[poz]]=poz;
                    where[ind[2*poz+1]]=2*poz+1;
                    poz=2*poz+1;
                }
            }
        }
};

heap a;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    int q;
    cin>>q;
    while(q--) {
        int tip;
        cin>>tip;
        if(tip==1) {
            int x;
            cin>>x;
            a.in(x);
        }
        if(tip==2) {
            int x;
            cin>>x;
            a.out(x);
        }
        if(tip==3) {
            cout<<a.get_min()<<"\n";
        }
    }
    return 0;
}