Cod sursa(job #2445612)

Utilizator Briana_NeaguNeagu Briana Briana_Neagu Data 4 august 2019 21:46:27
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <bits/stdc++.h>
#define max 200005


using namespace std;

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

int tree[max], nr;
bool poz[max];
vector <int> v(0, max);

void insert(int x, int nod, const int id)
{

    if (nod  == 1)
        tree[1] = id;
    else if (nod && x < v[tree[nod / 2]])
    {
        swap(tree[nod / 2], tree[nod]);
        insert(x, nod / 2, id);
    }
}

void update(int nod)
{

  int cur = nod;
  bool ok = 0;
  if (nod * 2  <= nr && v[tree[cur]] > v[tree[nod * 2]])
  {
      cur = nod * 2;
      ok = 1;
  }
  if (nod * 2 + 1  <= nr && v[tree[cur]] > v[tree[nod * 2 + 1]])
  {
      cur = nod * 2 + 1;
      ok = 1;
  }

  if (ok)
  {
      swap(tree[nod], tree[cur]);
      update(cur);
  }

}

int find_min()
{
    while(poz[tree[1]] == 1)
    {
        tree[1] = tree[nr];
        nr --;
        update(1);
    }
    return v[tree[1]];
}


int main()
{
    int q;
    f >> q;
    while (q --)
    {
       int op, x;
       f >> op;
       if (op == 3)
           g << find_min() << '\n';
       else
       {
           f >> x;
           if (op == 2)
               poz[x - 1] = 1;
           else
           {
               v.push_back(x);
               nr ++;
               tree[v.size()] = v.size() - 1;
               insert(x, v.size(), v.size() - 1);
           }
       }
    }
}