Cod sursa(job #2028575)

Utilizator danny794Dan Danaila danny794 Data 28 septembrie 2017 08:05:15
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 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;

  void insert(int value) {
    length++;
    int pos = length;
    values[pos] = value;
    _position[pos] = pos;
    _heap[pos] = pos;
    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;

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

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

  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;
  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;
}