Cod sursa(job #1560248)

Utilizator narcis_vsGemene Narcis - Gabriel narcis_vs Data 2 ianuarie 2016 12:25:01
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include<cstdio>
#include<algorithm>
using namespace std;
const int nmax = 200005;
int m, op, i, cnt, k, a[nmax], h[nmax], poz[nmax];
void heapup(int s)
{
    int f = s / 2;
    if(!f) return;
    if(a[h[f]] > a[h[s]])
    {
        swap(poz[h[f]], poz[h[s]]);
        swap(h[f], h[s]);
        heapup(f);
    }
}

void heapdown(int f)
{
    int s = f * 2;
    if(s > cnt) return;
    if(s < cnt && a[h[s + 1]] < a[h[s]]) s++;
    if(a[h[f]] > a[h[s]])
    {
        swap(poz[h[f]], poz[h[s]]);
        swap(h[f], h[s]);
        heapdown(s);
    }
}

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

    scanf("%d", &m);

    for(; m; m--)
    {
        scanf("%d", &op);

        if(op == 1)
        {
            scanf("%d", &a[++i]);
            h[++cnt] = i;
            poz[i] = cnt;
            heapup(cnt);
        }
        else if(op == 2)
        {
            scanf("%d", &k);
            poz[h[cnt]] = poz[k];
            h[poz[k]] = h[cnt];
            cnt--;
            heapdown(poz[k]);
        }
        else printf("%d\n", a[h[1]]);
    }

    return 0;
}