Cod sursa(job #1002708)

Utilizator Dddarius95Darius-Florentin Neatu Dddarius95 Data 28 septembrie 2013 16:33:34
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.02 kb
#include <fstream>
#include <algorithm>
#include <bitset>
#define Nmax 200099
#define Father(i) i/2
#define LeftSon(i) 2*i
#define RightSon(i) 2*i+1
using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");

int N,n,H[Nmax],v[Nmax],w[Nmax],nr;
bitset <Nmax>Eliminat(0);

inline void Swapp(int a,int b)
{
    swap(w[a],w[b]);
    v[w[a]]=a;
    v[w[b]]=b;
    swap(H[a],H[b]);
}


void Sift(int H[], int n,int nod)
{
    int Son=0;
    do
    {
        Son=0;
        // Alege un fiu mai mare ca tatal.
        if (LeftSon(nod)<=n)
        {
            Son=LeftSon(nod);
            if( RightSon(nod)<=n && H[RightSon(nod)]<H[LeftSon(nod)] ) Son=RightSon(nod);
            if (H[Son]>=H[nod]) Son=0;
        }
        if (Son)
        {
            Swapp(nod,Son);
            nod=Son;

        }
    } while(Son);
}

inline void Percolate(int H[], int n,int nod)
{
    int key=H[nod],aux=w[nod];
    while (nod>1 && key<H[Father(nod)])
    {
        Swapp(nod,Father(nod));
        nod=Father(nod);
    }
    H[nod]=key;
    //v[aux]=nod;
    //w[nod]=aux;
}


inline void DeleteHeap(int H[], int &n,int x)
{
    int nod=v[x];
    Swapp(v[x],n);
    --n;
    Percolate(H,n,nod);
    Sift(H,n,nod);
}

inline void InsertHeap(int H[], int &n,int key)
{
    H[++n]=key;
    nr++;
    v[nr]=n;
    w[n]=nr;
    Percolate(H,n,n);
}

int main()
{
    f>>N;
    for(int i=1;i<=N;i++)
    {
        int tip;
        f>>tip;
        switch (tip)
        {
            case 1:
            {
                int key;
                f>>key;
                InsertHeap(H,n,key);
                break;
            }
            case 2:
            {
                int x;
                f>>x;
                DeleteHeap(H,n,x);
                break;
            }
            case 3:
            {
                g<<H[1]<<'\n';
                break;
            }
            default: break;
        }
    }
    f.close();g.close();
    return 0;
}