Cod sursa(job #785493)

Utilizator round1First Round round1 Data 9 septembrie 2012 10:59:56
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include <cstdio>
#include <algorithm>
using namespace std;
#define Max 200001

struct heap{
    int x,n;
    heap()
    {
        x = 0;
        n = 0;
    }
} h[Max];
int n,k,pos[Max];

int add(int x)
{
    k++; // introducem un element nou in heap
    n++; // elementul intrat al n-lea
    h[k].x = x; // am setat valoarea
    h[k].n = n; // am setat nr de ordine la intrare
    pos[n] = k; // am setat pozitia el. intrat al n-lea ca fiind ultima in heap
    int t,f;
    f = k; t = f/2;
    while(t > 0 && h[t].x > h[f].x)
    {
        swap(h[t],h[f]);
        swap(pos[h[t].n],pos[h[f].n]);
        f = t; t = f/2;
    }
}

int remove(int x)
{
    int t,f;
    t = pos[x];
    h[t] = h[k--];
    pos[h[t].n] = t;
    f = 2*t;
    if(f+1 <= k && h[f+1].x < h[f].x)f++;
    while(f <= k && h[f].x < h[t].x)
    {
        swap(h[t],h[f]);
        swap(pos[h[t].n],pos[h[f].n]);
        t = f; f = 2*t;
        if(f+1 <= k && h[f+1].x < h[f].x)f++;
    }
}

int main()
{
    int m,c,x;
    freopen("test.in","r",stdin);
    freopen("test.out","w",stdout);

    scanf("%d",&m);
    while(m--)
    {
        scanf("%d",&c);
        if(c == 3)printf("%d\n",h[1].x); else
        {
            scanf("%d",&x);
            if(c == 1)add(x); else remove(x);
        }
    }

    return 0;
}