Cod sursa(job #2001750)

Utilizator vladbatalanBatalan Vlad vladbatalan Data 17 iulie 2017 16:35:45
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.39 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

int m, n, ntot, op, h[200010], v[200010], pz[200010];

void adauga(int x)
{
    while(v[h[x]] && v[h[x]] < v[h[x/2]])
    {
        swap(h[x], h[x/2]);
        swap(pz[h[x]], pz[h[x/2]]);
        x/=2;
    }
}

void sterge(int x)
{
    swap(h[x], h[n]);
    swap(pz[h[x]], pz[h[n]]);
    n--;
    if(v[h[x]] && v[h[x]] < v[h[x/2]])
    {
        while(v[h[x]] && v[h[x]] < v[h[x/2]])
        {
            swap(h[x], h[x/2]);
            swap(pz[h[x]], pz[h[x/2]]);
            x/=2;
        }
    }
    else
    {
        int y=0;
        while(x!=y)
        {
            y = x;
            if(2*x <= n &&v[h[x]] > v[h[2*x]]) y = 2*x;
            if(2*x+1<=n && v[h[x]] > v[h[2*x+1]]) y = 2*x+1;
            swap(h[x], h[y]);
            swap(pz[h[x]], pz[h[y]]);
        }
    }
}

int main()
{
    int x;
    fin >> m;
    for(int i=1; i<=m; i++)
    {
        fin >> op;
        if(op == 1)
        {
            fin >> x;

            n++;
            ntot++;
            v[ntot] = x;
            h[n] = ntot;
            pz[ntot] = n;

            adauga(n);
        }
        if(op == 2)
        {
            fin >> x;
            sterge(pz[x]);
        }
        if(op == 3)
            fout<<v[h[1]]<<'\n';
    }
    return 0;
}