Cod sursa(job #1816364)

Utilizator crazylamaRiclea Andrei crazylama Data 26 noiembrie 2016 13:27:20
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.75 kb
#include <fstream>
#include <vector>
#define NMAX 200001
using namespace std;

ifstream f("heapuri.in");
ofstream g("heapuri.out");

vector<int> poz(NMAX), val(NMAX);

int FatherOfNode(int Node)
{
    return Node / 2;
}

int LeftSon(int Node)
{
    return Node * 2;
}

int RightSon(int Node)
{
    return Node * 2 + 1;
}

int GetMin(vector<int> v)
{
    return v[1];
}

void InsertNode(vector<int> &v, int &n, int x)
{
    int father;
    v[++n] = x;
    poz[n] = n;
    father = FatherOfNode(n);
    int son = n;
    while (v[father] > v[son])
    {
        swap(v[father], v[son]);
        swap(poz[father], poz[son]);
        son = father;
        father = FatherOfNode(son);
    }
}

void sift(vector<int> &v, int n, int k)
{
    int son = 0;
    do
    {
        if (LeftSon(k) <= n)
            son = LeftSon(k);
        if (RightSon(k) <= n && v[RightSon(k)] < v[son])
            son = RightSon(k);
        if (v[k] <= v[son])
            son = 0;
        if (son)
        {
            swap(v[k], v[son]);
            swap(poz[k], poz[son]);
            k = son;
        }
    } while (son);
}

void EraseNode(vector<int> &v, int &n, int x)
{
    swap(v[n], v[val[x]]);
    --n;
    sift(v, n, val[x]);
}

int main()
{
    int n, p, nr = 0, x;
    vector<int> v(NMAX);
    f >> n;
    for (int i = 1; i <= n; ++i)
    {
        f >> p;
        if (p == 1)
        {
            f >> x;
            InsertNode(v, nr, x);
            for (int i = 1; i <= nr; ++i)
                val[poz[i]] = i;
        }
        else if (p == 2)
        {
            f >> x;
            EraseNode(v, nr, x);
        }
        else if (p == 3)
            g << GetMin(v) << "\n";
    }
    return 0;
}