Cod sursa(job #2077722)

Utilizator mihai.alphamihai craciun mihai.alpha Data 28 noiembrie 2017 15:08:39
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.9 kb
#include <bits/stdc++.h>

using namespace std;

const int maxn = 2e5 + 5;

int heap[maxn], dimh;///invheap imi spune ce cheie are x
unordered_map <int, int> invheap;
int v[maxn], n;

inline void SWAP(int noda, int nodb)  {
    swap(heap[noda], heap[nodb]);
    swap(invheap[heap[noda]], invheap[heap[nodb]]);
}

inline void upheap(int nod)  {
    while(nod > 1 && heap[nod] < heap[nod / 2])  {
        SWAP(nod, nod / 2);
        nod /= 2;
    }
}

inline void downheap(int nod)  {
    while(1)  {
        int lson = nod * 2;
        int rson = nod * 2 + 1;
        if(lson <= dimh)  {
            if(rson <= dimh)  {
                if(heap[lson] >= heap[nod] && heap[rson] >= heap[nod])
                    return;
                if(heap[lson] <= heap[rson])  {
                    SWAP(lson, nod);
                    nod = lson;
                }
                else  {
                    SWAP(rson, nod);
                    nod = rson;
                }
            }
            else  {
                if(heap[lson] >= heap[nod])
                    return;
                SWAP(lson, nod);
                nod = lson;
            }
        }
        else  {
            return;
        }
    }
}

int main()  {
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);
    int nrop;
    cin >> nrop;
    while(nrop--)  {
        int o, x;
        cin >> o;
        if(o == 1)  {
            cin >> x;
            v[++n] = x;
            dimh++;
            heap[dimh] = x;
            invheap[x] = dimh;
            upheap(dimh);//urc pozitia dimh
        }
        else if(o == 2)  {
            cin >> x;///trb sa tai v[x]
            int nod = invheap[v[x]];
            SWAP(nod, dimh);
            dimh--;
            downheap(nod);
        }
        else  {
            cout << heap[1] << "\n";
        }
    }
    return 0;
}