Cod sursa(job #1946046)

Utilizator andreigasparoviciAndrei Gasparovici andreigasparovici Data 29 martie 2017 21:01:22
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.48 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/2] > heap[n])
    {
        pos[heap[n/2]] = n;
        pos[heap[n]] = n/2;
        swap(heap[n/2],heap[n]);

        heap_update(n/2);
    }
}

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


void heap_resolve(int nod)
{

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

    int left = INFINIT, right = INFINIT;

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

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

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

class InParser
{
    char *b;
    int bi, bs;
    FILE *in;
    inline bool isdigit(char c)
    {
        return c>='0' && c<='9';
    }
public:
    InParser(const char *s)
    {
        in = fopen(s,"r");
        fseek(in,0,SEEK_END);
        bs = ftell(in);
        b = new char[bs+1];
        fseek(in,0,SEEK_SET);
        fread(b,1,bs,in);
        bi = 0;
    }
    InParser& operator>>(int &x)
    {
        x = 0;
        while(!isdigit(b[bi]))
            bi++;
        while(isdigit(b[bi]))
        {
            x = x * 10 + b[bi] - '0';
            ++bi;
        }
        return *this;
    }
};

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

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