Cod sursa(job #1517807)

Utilizator tudormaximTudor Maxim tudormaxim Data 4 noiembrie 2015 21:18:35
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.36 kb
#include <iostream>
#include <cstdio>
using namespace std;
const int nmax = 200005;
int heap[nmax], poz[nmax], v[nmax], dim, lg;

void Swap(int x, int y)
{
    int aux=heap[x];
    heap[x]=heap[y];
    heap[y]=aux;
    poz[heap[x]]=x;
    poz[heap[y]]=y;
}

void heap_down(int dad)
{
    int lson=(dad<<1), rson=(dad<<1|1), node=dad;
    if(lson<=dim && v[heap[lson]]<v[heap[node]]) node=lson;
    if(rson<=dim && v[heap[rson]]<v[heap[node]]) node=rson;
    if(node!=dad)
    {
        Swap(node, dad);
        heap_down(node);
    }
}

void heap_up(int son)
{
    int dad=(son>>1);
    while(son>1 && v[heap[dad]]>v[heap[son]])
    {
        Swap(dad, son);
        son=son>>1;
    }
}

int main()
{
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);
    int n, op, i, x, p;
    scanf("%d", &n);
    for(i=1; i<=n; i++)
    {
        scanf("%d", &op);
        if(op==1)
        {
            scanf("%d", &v[++lg]);
            heap[++dim]=lg;
            poz[lg]=dim;
            heap_up(dim);
        }
        else if(op==2)
        {
            scanf("%d", &x);
            p=poz[x];
            Swap(p, dim);
            dim--;
            heap_up(p);
            heap_down(p);
        }
        else printf("%d\n", v[heap[1]]);
    }
    fclose(stdin);
    fclose(stdout);
    return 0;
}