Cod sursa(job #1319633)

Utilizator claudiu.gatinaFMI Claudiu Gatina claudiu.gatina Data 17 ianuarie 2015 11:37:38
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include <iostream>
#include <fstream>
#include <algorithm>

using namespace std;
#define maxn 200010
#define maxh 1000000010
long long int v[maxn], h[maxn], poz[maxn];
int nv, nh;

void up(int n)
{
    while (n/2 && v[h[n]]<v[h[n/2]])
    {
        swap(poz[h[n]], poz[h[n/2]]);
        swap(h[n], h[n/2]);
        n/=2;
    }
}

void down(int n)
{
    while(n<=nh/2)
    {
        if(v[h[n]]>v[h[2*n]] || v[h[n]]>v[h[2*n+1]])
        {
            if(v[h[2*n]]<v[h[2*n+1]])
            {
                swap(poz[h[n]], poz[h[2*n]]);
                swap(h[n],h[2*n]);
            }
            else
            {
                swap(poz[h[n]], poz[h[2*n]]);
                swap(h[n],h[2*n+1]);
            }
        }
        else return;
        n*=2;
    }
}

void ddown(int n)
{
    int m=n;
    while (m<=nh)
    {
        m=2*n;
        if (2*n<nh && v[h[2*n]]<v[h[2*n+1]]) m=2*n;
        if (2*n+1<nh && v[h[2*n]]>v[h[2*n+1]]) m=2*n+1;
        if (m<=nh && v[h[n]]>v[h[m]])
        {
            swap(poz[h[n]], poz[h[m]]);
            swap(h[n], h[m]);
        }
        n=m;
    }
}
void take(int n)
{
    h[n]=h[nh];
    h[nh]=0;
    nh--;
    if (n>1 && v[h[n]]<v[h[n/2]])
        up(n);
    else down(n);
}

int main()
{
    ifstream f("heapuri.in");
    ofstream g("heapuri.out");
    v[0]=maxh;
    int n, op, i, x;
    f>>n;
    for (i=1;i<=n;i++)
    {
        f>>op;
        if (op==3)
            g<<v[h[1]]<<'\n';
            else
        {
            f>>x;
            if (op==1)
            {
                nh++; nv++;
                v[nv]=x;
                h[nh]=nv;
                poz[nv]=nh;
                up(nh);
            }
            if (op==2)
                take(poz[x]);
        }
    }
}