Cod sursa(job #1816206)

Utilizator crazylamaRiclea Andrei crazylama Data 26 noiembrie 2016 11:16:40
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.88 kb
#include <fstream>
#include <vector>
#include <utility>
#define NMAX 200001
using namespace std;

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

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< pair<int, int> > v)
{
    return v[1].first;
}

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

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

int FindNode(vector< pair<int, int> > &v, int n, int x)
{
    for (int i = 1; i <= n; ++i)
        if (v[i].second == x)
            return i;
}

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

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