Cod sursa(job #1094875)

Utilizator ovidel95Ovidiu ovidel95 Data 29 ianuarie 2014 22:49:59
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
#include <fstream>
#include<algorithm>
#define NMAX 200001
using namespace std;
int heap[NMAX],n,care[NMAX],nc;
ofstream g("heapuri.out");
void sift(int k)
{
    int son,aux;
    do
    {
        son=0;
        if(k*2<=n)
        {
            son=k*2;
            if(k*2+1<n&&heap[k*2+1]<heap[son])
                son=k*2+1;
            if(heap[son]>=heap[k])
                son=0;
        }
        if(son)
        {
            aux=heap[son];
            heap[son]=heap[k];
            heap[k]=aux;
            k=son;
        }
    }while(son);

}

void percolate(int k)
{
    int key=heap[k];
    while(k>1&&key<heap[k/2])
    {
        heap[k]=heap[k/2];
        k=k/2;
    }
    heap[k]=key;
}
int cauta(int x)
{
    int k=0,i=1;
    while(i<=n&&k==0)
    {
        if(heap[i]==x)
            k=1;
        else
            i++;
    }
    return i;

}
void cut(int k)
{
    heap[k]=heap[n];
    n--;
    if(k>1&&heap[k]<heap[k/2])
        percolate(k);
    else sift(k);

}

int main()
{
    ifstream f("heapuri.in");
    int tip,nr,n2;
    n=0; nc=0;
    f>>n2;
    for(int i=1;i<=n2;i++)
    {
        f>>tip;
        if(tip==1)
        {
            f>>nr;
            nc++;
            n++;
            care[nc]=nr;
            heap[n]=nr;
            percolate(n);
        }
        if(tip==2)
        {
           f>>nr;
           cut(cauta(care[nr]));
        }
        if(tip==3)
        {
            g<<heap[1]<<"\n";
        }

    }
    f.close();
    g.close();
    return 0;
}