Cod sursa(job #1254531)

Utilizator LycrsTrifan Tamara Lycrs Data 2 noiembrie 2014 21:15:43
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include <fstream>
using namespace std;
ifstream cin("heapuri.in");
ofstream cout("heapuri.out");
const int MAX=10005;

int t, o, i, j, h[MAX], n, k, a[MAX], m, index[MAX], xedni[MAX], x;

void upheap()
{

    while (k>1 && h[k]<h[k/2])
    {
        swap(h[k], h[k/2]);
        swap(index[xedni[k]], index[xedni[k/2]]);
        swap(xedni[k], xedni[k/2]);
        k/=2;
    }

}

void downheap()
{
    int nod;
    do
    {
        nod=0;
        if (k*2<=n) nod=k*2;
        if (k*2+1<=n && h[2*k+1]<h[2*k])
        nod=k*2+1;
        if (h[nod]>=h[k]) nod=0;

    if (nod)
    {
        swap(h[k], h[nod]);
        swap(index[xedni[h[k]]], index[xedni[h[nod]]]);
        swap(xedni[h[k]], xedni[h[nod]]);
        k=nod;
    }
} while (nod);
}


void cut() {
    h[k] = h[n];
    --n;

    if ((k > 1) && (h[k] < h[k/2])) {
        upheap();
    } else {
        downheap();
    }
}

int main()
{
    cin>>t;
    while(t--)
    {
        cin>>o;
        if (o==3) cout<<h[1]<<'\n';
        if (o==1)
        {
            cin>>x;
            h[++n]=x;
            index[++i]=n;
            k=n;
            xedni[n]=index[i];
            upheap();
        }
        if (o==2)
        {
            cin>>x; k=index[x];
            cut();
        }
    }
    return 0;
}