Cod sursa(job #2023753)

Utilizator rangal3Tudor Anastasiei rangal3 Data 19 septembrie 2017 14:06:53
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include <fstream>
#define in "heapuri.in"
#define out "heapuri.out"
#define N 200003

using namespace std;

ifstream fin(in);
ofstream fout(out);

int n,p,x;
int heap[N],leg[N]; // leg[i] = j, elementul intrat pe pozitia i se afla pe pozitia j.
int hn,legn; // legn - cate elemente s-au adaugat in leg[]. hn - cate elemente se mai afla in heap.

inline int swap(int &a,int &b)
{
    int aux = a;
    a = b;
    b = aux;
}

inline int father(const int &x)
{
    return x/2;
}

inline int left_son(const int &x)
{
    return x*2;
}

inline int right_son(const int &x)
{
    return x*2 + 1;
}

inline void percolate(const int &hn)
{
    int son;
    int poz = hn; // pozitia actuala a lui heap[hn]
    while(poz > 1)
    {
        if(heap[father(poz)] >  heap[poz])
        {
            swap(heap[father(poz)], heap[poz]);
            swap(leg[father(poz)], leg[poz]);

            poz = father(poz);
        }
        else poz = 0;
    }
}

inline void insereaza(const int &x)
{
    heap[++hn] = x;
    leg[++legn] = hn;
    percolate(hn);
}


int main()
{
    fin>>n;
    while(n--)
    {
        fin>>p;
        switch(p)
        {
            case 1: fin>>x;
            insereaza(x);
            break;
            case 2: fin>>x;
            //sterge(leg[x]);
            break;
            default: fout<<heap[1]<<"\n";
            break;
        }
    }


    fin.close(); fout.close();
    return 0;
}