Cod sursa(job #1946033)

Utilizator andreigasparoviciAndrei Gasparovici andreigasparovici Data 29 martie 2017 20:53:29
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.68 kb
#include <iostream>
#include <cstdio>
#define MAXN 200005
#define INFINIT 0x3f3f3f3f
#define fastcall __attribute__((optimize("-O3")))
#define inline __inline__ __attribute__((always_inline))
using namespace std;


int q, n, k;
int heap[MAXN];
int ins[MAXN];

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

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

fastcall int heap_find(int nod, int val)
{
    if(nod > n)
        return -1;
    if(val == heap[nod])
        return nod;

    if(val < heap[nod])
        return -1;

    int x = heap_find((nod<<1), val);

    if(x!=-1) return x;

    return heap_find((nod<<1)+1,val);
}

fastcall 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)
    {
        swap(heap[nod],heap[(nod<<1)]);
        heap_resolve((nod<<1));
    }
    else if(heap[(nod<<1)+1] < heap[nod] && (nod<<1) +1 <=n)
    {
        swap(heap[nod],heap[(nod<<1)+1]);
        heap_resolve((nod<<1)+1);
    }
}

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

class InParser
{
    char *b;
    int bi, bs;
    FILE *in;
    inline fastcall 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;
    }
    inline fastcall 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  = heap_find(1,ins[x]);
            heap_remove(pos_heap);
        }
    }
    return 0;
}