Cod sursa(job #1850446)

Utilizator NarniussAnghelache Bogdan Narniuss Data 18 ianuarie 2017 17:52:41
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.82 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#define MAX_HEAP_SIZE 200001
using namespace std;

typedef int Heap[MAX_HEAP_SIZE];

int ordine[MAX_HEAP_SIZE], pozitie[MAX_HEAP_SIZE];

inline int father(int nod){
  return nod >> 1;
}

inline int left_son(int nod){
  return nod << 1;
}

inline int right_son(int nod){
  return nod << 1 + 1;
}

//Coboram nodul K in heap pana ajunge pe o pozitie potrivita
void sift(Heap H, int N, int K) {
    int son;
    do {
        son = 0;

        if (left_son(K) <= N) {
            son = left_son(K);
            if (right_son(K) <= N && H[right_son(K)] < H[left_son(K)]) {
                son = right_son(K);
            }
            if (H[son] >= H[K]) {
                son = 0;
            }
        }

        if (son) {
            swap(H[K], H[son]);
            K = son;
            pozitie[H[K]] = K;
        }
    } while (son);
}
//Urcam nodul K in heap pana ajunge pe o pozitie favorabila
void percolate(Heap H, int N, int K){
  int key = H[K];

  while(K > 1 && (key < H[father(K)])){
    pozitie[H[father(K)]] = K;
    H[K] = H[father(K)];
    K = father(K);

  }

  H[K] = key;
  pozitie[H[K]] = K;
}

void insert(Heap H, int &N, int val){
  H[++N] = val;
  ordine[N] = val;
  percolate(H, N, N);
}

void del(Heap H, int &N, int K){
  H[K] = H[N];
  --N;

  if((K > 1) &&(H[K] < H[father(K)])){
    percolate(H, N, K);
  }else{
    sift(H, N, K);
  }
}

int minim_heap(Heap H){
  return H[1];
}
int main()
{
  ifstream fin("heapuri.in");
  ofstream fout("heapuri.out");
  Heap H;
  int m, op, x, N = 0,i;
  fin>>m;
  for( i = 1 ; i <= m ; i++){
    fin>>op;
    switch (op) {
      case 1: fin >> x; insert(H, N, x); break;
      case 2: fin >> x; del(H, N, pozitie[ordine[x]]); break;
      case 3: fout << minim_heap(H)<< "\n"; break;
    }
  }



  fin.close();
  fout.close();
  return 0;
}