Cod sursa(job #734866)

Utilizator a08iAndrei Ionescu a08i Data 15 aprilie 2012 02:38:55
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.69 kb
#include<iostream>
#include<vector>
#include<cstdio>

using namespace std;


class MinHeap
{
  vector<int> heap;
  vector<int> loc;
  vector<int> nr;

  void siftup(int what)
  {
    int parent = what / 2;
    if(nr[heap[parent]] > nr[heap[what]])
    {
      swap(heap[parent], heap[what]);
      loc[heap[parent]] = parent;
      loc[heap[what]] = what;
      siftup(parent);
    }
  }


  void siftdown(int where)
  {
    int lft = where * 2;
    int rgt = where * 2 + 1;

    int maxindex = heap.size() -1;

    if(rgt <= maxindex)
    {
      if(nr[heap[lft]] < nr[heap[rgt]])
      {
        if(nr[heap[where]] > nr[heap[lft]])
        {
          swap(heap[where], heap[lft]);
          loc[heap[where]] = where;
          loc[heap[lft]] = lft;
          siftdown(lft);
        }
      }
      else
      {
        if(nr[heap[where]] > nr[heap[rgt]])
        {
          swap(heap[where], heap[rgt]);
          loc[heap[where]] = where;
          loc[heap[rgt]] = rgt;
          siftdown(rgt);
        }
      }
    }
    else if(lft <= maxindex)
    {
      if(nr[heap[where]] > nr[heap[lft]])
      {
        swap(heap[where], heap[lft]);
        loc[heap[where]] = where;
        loc[heap[lft]] = lft;
        siftdown(lft);
      }
    }


  }

  public:
  MinHeap(int n)
  {
    heap.reserve(n);
    nr.reserve(n);
    loc.reserve(n);
  }

  void insert(int value)
  {
    nr.push_back(value);
    int nth = nr.size()-1;
    heap.push_back(nth);
    loc[nth] = heap.size()-1;
    siftup(heap.size()-1);
  }

  int showmin()
  {
    return nr[heap[0]];
  }

  void remove(int nth)
  {

    /*if(nth == 18)
    {
      for(int i=0; i<nr.size(); i++)
      {
        cout << "   " << i << " " << nr[i] << " "<<endl;
      }
    }*/

    int where = loc[nth-1];
    //cout << "where " << where<<endl;
    loc[nth-1] = -1;
    swap(heap[where], heap[heap.size()-1]);
    heap.pop_back();
    loc[heap[where]] = where;
    siftdown(where);
  }

  void print()
  {
    for(int i=0; i<heap.size(); i++)
    {
      cout << " " << nr[heap[i]] << endl;
    }
  }

};



int main()
{

  freopen("heapuri.in", "r", stdin);
  freopen("heapuri.out", "w", stdout);

  int N, Type, X;
  scanf("%d", &N);

  MinHeap myheap(1000000);

  for(int i=0; i<N; i++)
  {
    scanf("%d", &Type);

    if(Type != 3)
    {
      scanf("%d", &X);
    }

    switch(Type)
    {
      case 1:
        //cout << "inserting " << X<<endl;
        myheap.insert(X);
        //myheap.print();
        break;
      case 2:
        //cout << "removing " << X <<endl;
        myheap.remove(X);
        //myheap.print();
        break;
      case 3:
        //cout << "min ";
        printf("%d\n", myheap.showmin());
        //cout <<endl;
        break;
    }

  }

  return 0;
}