Cod sursa(job #2017257)

Utilizator PetrescuAlexandru Petrescu Petrescu Data 31 august 2017 17:38:49
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.81 kb
#include <iostream>
#include <fstream>
#include <vector>
#define MAX_HEAP_SIZE 200000

using namespace std;
vector <int> elem;
int v[MAX_HEAP_SIZE];
int gasit;
inline int father(int k)
{
  return k / 2;
}
inline int left_son(int k)
{
  return k * 2;
}
inline int right_son(int k)
{
  return k * 2 + 1;
}
inline int min()
{
  return v[1];
}
inline void search(int n, int poz, int k)
{
  if(v[poz] == k)gasit = poz;
  else
  {
    if(poz * 2 <= n)search(n, poz * 2, k);
    if(poz * 2 + 1 <= n)search(n, poz * 2 + 1, k);
  }
}
inline void sift(int n, int k)
{
  int son;

  do
  {
    son = 0;
    if(left_son(k) <= n)
    {
      son = left_son(k);
      if(right_son(k) <= n && v[right_son(k)] < v[son])son = right_son(k);
      if(v[son] < v[k])
      {
        swap(v[son], v[k]);
        k = son;
      }
      else son = 0;
    }
  }while(son != 0);
}
inline void percolate(int k)
{
  while(k > 1 && v[father(k)] > v[k])
  {
    swap(v[father(k)], v[k]);
    k = father(k);
  }
}
inline void insert(int& n, int elem)
{
  v[++n] = elem;
  percolate(n);
}
inline void cut(int& n, int poz)
{
  v[poz] = v[n];
  n--;
  if(v[poz] > v[left_son(poz)] || v[poz] > v[right_son(poz)])sift(n, poz);
  else percolate(poz);
}
int main()
{
  int n, operatie, k, lungime = 0;

  ifstream in;
  ofstream out;
  in.open("heapuri.in");
  out.open("heapuri.out");
  in >> n;
  for(int i = 1; i <= n; i++)
  {
    in >> operatie;
    if(operatie == 1 || operatie == 2)
    {
      in >> k;
      if(operatie == 1)
      {
        insert(lungime, k);
        elem.push_back(k);
      }
      else
      {
        search(lungime, 1, elem[k - 1]);
        cut(lungime, gasit);
      }
    }
    else out << min() << endl;
  }
  in.close();
  out.close();
  return 0;
}