Cod sursa(job #2028580)

Utilizator danny794Dan Danaila danny794 Data 28 septembrie 2017 08:57:37
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
#include <cstdio>

#define NMAX 200001

void swap(int& a, int& b) {
  int c = a;
  a = b;
  b = c;
}

struct heap {
  int values[NMAX];
  int _position[NMAX];
  int _heap[NMAX];
  int length;
  int count;

  void insert(int value) {
    values[++count] = value;
    _heap[++length] = count;
    _position[count] = length;
    int pos = length;
    while (pos > 1 && values[_heap[pos]] < values[_heap[pos / 2]]) {
      swap(pos, pos / 2);
      pos /= 2;
    }
  }

  void swap(int a, int b) {
    int aux;
    aux = _heap[a];
    _heap[a] = _heap[b];
    _heap[b] = aux;

    _position[_heap[a]] = a;
    _position[_heap[b]] = b;
  }

  void remove(int pos) {
    pos = _position[pos];
    swap(pos, length--);
    while (true) {
      int aux = pos;
      if (length >= pos * 2 && values[_heap[pos]] > values[_heap[pos * 2]]) {
        aux = 2 * pos;
      }
      if (length >= pos * 2 + 1 && values[_heap[aux]] > values[_heap[pos * 2 + 1]]) {
        aux = 2 * pos + 1;
      }
      if (aux == pos) {
        break;
      }
      swap(pos, aux);
      pos = aux;
    }
  }

  inline int readMin() {
    return values[_heap[1]];
  }
};

int main() {
  freopen("heapuri.in", "r", stdin);
  freopen("heapuri.out", "w", stdout);
  int n, value, position, op;
  heap myHeap;
  myHeap.length = 0;
  myHeap.count = 0;
  scanf("%d", &n);
  while (n-- > 0) {
    scanf("%d", &op);
    switch (op) {
      case 1:
        scanf("%d", &value);
        myHeap.insert(value);
        break;
      case 2:
        scanf("%d", &position);
        myHeap.remove(position);
        break;
      case 3:
        printf("%d\n", myHeap.readMin());
        break;
    }
  }
  return 0;
}