Cod sursa(job #2539171)

Utilizator Briana_NeaguNeagu Briana Briana_Neagu Data 5 februarie 2020 18:37:54
Problema Heapuri Scor 100
Compilator cpp-32 Status done
Runda Arhiva educationala Marime 2.2 kb
#include <bits/stdc++.h>

using namespace std;

const int maxVal = 1e6 + 5;

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

class Heap
{
public:
    Heap(int n)
    {
        lastAdded = 0;
        tree.resize(n + 10);
        a.reserve(n + 2);
        flag.reserve(n + 2);
    }
    void add(const int value)
    {
        a.push_back(value);
        flag.push_back(0);
        tree[++ lastAdded] = a.size() - 1;
        private_add(lastAdded, value);
    }

    void erase(int id)
    {
        flag[-- id] = true;
    }

    int query()
    {
        while (flag[tree[1]])
        {
            tree[1] = tree[lastAdded];
            lastAdded --;
            private_pop(1, a[tree[1]]);
        }
        return a[tree[1]];
    }

private:
    int lastAdded = 0;
    vector <int> a;
    vector <int> flag;
    vector <int> tree;

    void private_add(int currentNode, const int value)
    {
      if (currentNode == 1)
          return;
      int father = currentNode / 2;
      assert(father < a.size());
      if (a[tree[father]] > value)
      {
          swap(tree[father], tree[currentNode]);
          private_add(father, value);
      }
    }

    void private_pop(int currentNode, int value)
    {
        int minim = value;
        int where = -1;
        if (currentNode * 2 <= lastAdded && minim > a[tree[currentNode * 2]])
        {
            where = currentNode * 2;
            minim = a[tree[currentNode * 2]];
        }
        if (currentNode * 2 + 1 <= lastAdded && minim > a[tree[currentNode * 2 + 1]])
        {
            where = currentNode * 2 + 1;
            minim = a[tree[currentNode * 2 + 1]];
        }
        if (where != -1)
        {
            swap(tree[where], tree[currentNode]);
            private_pop(where, value);
        }

    }
};

int main()
{
   int n;
   f >> n;
    auto *Heap = new class Heap(n);
   for (int i = 1; i <= n; ++ i)
   {
       int op;
       f >> op;
       if (op == 1)
       {
           int val;
           f >> val;
           Heap -> add(val);
       }
       else if (op == 2)
       {
           int id;
           f >> id;
           Heap -> erase(id);
       }
       else
       {
           assert(op == 3);
           g << Heap -> query() << '\n';
       }
   }
}