Cod sursa(job #1946053)

Utilizator andreigasparoviciAndrei Gasparovici andreigasparovici Data 29 martie 2017 21:06:51
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.94 kb
#include <iostream>
#include <cstdio>
#include <unordered_map>
#define MAXN 200005
#define INFINIT 0x3f3f3f3f
using namespace std;

int q, n, k;
int heap[MAXN];
int ins[MAXN];
unordered_map<int,int> pos;

void heap_update(int n)
{
    if(heap[n>>1] > heap[n])
    {
        pos[heap[n>>1]] = n;
        pos[heap[n]] = n>>1;
        swap(heap[n>>1],heap[n]);
        heap_update(n>>1);
    }
}

void heap_insert(int x)
{
    ++n;
    heap[n]=x;
    pos[x] = n;
    heap_update(n);
}

void heap_resolve(int nod)
{

    if(((nod<<1) <=n && heap[nod] <= heap[(nod<<1)]) \
        && ((nod<<1)+1 <= n && heap[nod] <= heap[(nod<<1)+1]))
        return;

    int left = INFINIT, right = INFINIT;

    if((nod<<1) <= n)
        left = heap[(nod<<1)];
    if((nod<<1) +1 <= n)
        right = heap[(nod<<1) + 1];
    if(left == right)
        return;
    if(left < right && heap[(nod<<1)] < heap[nod] && (nod<<1) <=n)
    {
        pos[heap[nod]] = (nod<<1);
        pos[heap[(nod<<1)]] = nod;
        swap(heap[nod],heap[(nod<<1)]);
        heap_resolve((nod<<1));
    }
    else if(heap[(nod<<1)+1] < heap[nod] && (nod<<1) +1 <=n)
    {
        pos[heap[nod]] = (nod<<1) + 1;
        pos[heap[(nod<<1) + 1]] = nod;
        swap(heap[nod],heap[(nod<<1)+1]);
        heap_resolve((nod<<1)+1);
    }
}

void heap_remove(int nod)
{
    swap(heap[nod],heap[n]);
    pos[heap[nod]] = n;
    pos[heap[n]] = nod;
    --n;
    heap_resolve(nod);
}

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

    scanf("%d",&q);
    while(q--)
    {
        int op;
        scanf("%d",&op);
        if(op==1)
        {
            int x;
            scanf("%d",&x);
            heap_insert(x);
            ins[++k] = x;
        }
        else if(op==3)
            printf("%d\n",heap[1]);
        else if(op==2)
        {
            int x;
            scanf("%d",&x);
            int pos_heap  = pos[ins[x]];
            heap_remove(pos_heap);
        }
    }
    return 0;
}