Cod sursa(job #1843023)

Utilizator GoogalAbabei Daniel Googal Data 7 ianuarie 2017 23:28:59
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.18 kb
#include <fstream>
#include <algorithm>
#define HeapMax 200001

using namespace std;

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

int n,heap[HeapMax],v[HeapMax],z[HeapMax],code,x,nr,realno,r;

inline int father(int k)
{
    return k/2;
}

inline int leftson(int k)
{
    return k*2;
}

inline int rightson(int k)
{
    return k*2+1;
}

inline int minheap()
{
    return heap[1];
}

void sift(int n, int k)
{
    int son;
    do
    {
        son=0;
        if(leftson(k)<=n)
        {
            son=leftson(k);
            if(rightson(k)<=n && heap[leftson(k)]>heap[rightson(k)])
                son=rightson(k);
            if(heap[son]>=heap[k])
                son=0;
        }

        if(son)
        {
            swap(heap[k],heap[son]);
            k=son;
        }
    }
    while(son);
}

void percolate(int n, int k)
{
    int key=heap[k];
    while( k>1 && key<heap[father(k)])
    {
        heap[k]=heap[father(k)];
        k=father(k);
    }
    heap[k]=key;
}

void insert_elem(int &n, int key)
{
    heap[++n]=key;
    percolate(n,n);
}

void delete_elem(int &n, int k)
{
    heap[k]=heap[n];
    n--;
    if(k>1 && heap[k]<heap[father(k)])
        percolate(n,k);
    else
        sift(n,k);
}

///
void search_elem(int n,int key, int poz)
{
    if(heap[poz]==key)
        r=poz;
    else
    {
        if(leftson(poz)<=n && heap[leftson(poz)]<=key)
            search_elem(n, key, leftson(poz));
        if(rightson(poz)<=n && heap[rightson(poz)<=key])
            search_elem(n, key, rightson(poz));
    }
    //for(int i=1;i<=nr;i++)
    //  if(heap[i]==key)
    //    return i;
}
///

int main()
{
    fin>>n;
    for(int i=1; i<=n; i++)
    {
        fin>>code;
        if(code==1)
        {
            fin>>x;
            insert_elem(nr, x);
            v[++realno]=x;
            //z[realno]=nr;
        }
        else if(code==2)
        {
            fin>>x;
            search_elem(nr, v[x], 1);
            delete_elem(nr, r);
            //z[x]=0;
        }
        else
            fout<<minheap()<<'\n';
    }
    fin.close();
    fout.close();
    return 0;
}