Cod sursa(job #2812600)

Utilizator Teodor94Teodor Plop Teodor94 Data 4 decembrie 2021 19:48:46
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.07 kb
#include <stdio.h>
#include <algorithm>
using namespace std;

#define INSERT 1
#define ERASE 2
#define QUERY 3

#define MAX_N 200000

struct Node {
  int value, cron;
};

Node heap[MAX_N];
int heapSize;
int cronToHeap[MAX_N];

inline int parent(int node) { return (node - 1) / 2; }
inline int leftChild(int node) { return node * 2 + 1; }
inline int rightChild(int node) { return node * 2 + 2; }

void upHeap(int node) {
  if (node && heap[parent(node)].value > heap[node].value) {
    swap(heap[parent(node)], heap[node]);
    cronToHeap[heap[parent(node)].cron] = parent(node);
    cronToHeap[heap[node].cron] = node;

    upHeap(parent(node));
  }
}

void downHeap(int node) {
  int left, right, smallest;

  smallest = node;
  left = leftChild(node), right = rightChild(node);

  if (left < heapSize && heap[left].value < heap[smallest].value)
    smallest = left;
  if (right < heapSize && heap[right].value < heap[smallest].value)
    smallest = right;

  if (smallest != node) {
    swap(heap[node], heap[smallest]);
    cronToHeap[heap[node].cron] = node;
    cronToHeap[heap[smallest].cron] = smallest;

    downHeap(smallest);
  }
}

void insert(int value, int cron) {
  heap[heapSize] = {value, cron};
  cronToHeap[cron] = heapSize;
  upHeap(heapSize++);
}

void erase(int cron) {
  int node;

  node = cronToHeap[cron];

  heap[node] = heap[heapSize - 1];
  cronToHeap[heap[heapSize - 1].cron] = node;
  --heapSize;

  downHeap(node);
  upHeap(node);
}

inline int top() {
  return heap[0].value;
}

int main() {
  FILE *fin, *fout;
  fin = fopen("heapuri.in", "r");
  fout = fopen("heapuri.out", "w");

  int q, type, x, cronIndex;
  fscanf(fin, "%d", &q);

  cronIndex = 0;
  while (q--) {
    fscanf(fin, "%d", &type);

    if (type == INSERT) {
      fscanf(fin, "%d", &x);
      insert(x, cronIndex++);
    } else if (type == ERASE) {
      fscanf(fin, "%d", &x);
      erase(x - 1);
    } else if (type == QUERY)
      fprintf(fout, "%d\n", top());
  }

  fclose(fin);
  fclose(fout);
  return 0;
}