Cod sursa(job #2809834)

Utilizator Alex_HossuHossu Alexandru Alex_Hossu Data 27 noiembrie 2021 18:12:15
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <iostream>
#include <stdio.h>

#define MAX_N 200000

using namespace std;

int deleted[MAX_N+1];
int heapSize = 1, n = 1;

struct Node {
  int val;
  int pos;
};

Node heap[MAX_N + 1];

void myAdd(int val) {
  int i;

  heap[heapSize].val = val;
  heap[heapSize++].pos = n;

  n++;
  i = heapSize - 1;
  while ((i > 0) && (heap[i].val < heap[i / 2].val)) {
    swap(heap[i], heap[i / 2]);
    i = i / 2;
  }
}

void myDelete(int ind) {
  heap[ind].pos = heap[heapSize - 1].pos;
  heap[ind].val = heap[heapSize - 1].val;
  heapSize--;

  while ((2 * ind < heapSize) && (heap[ind].pos > min(heap[2 * ind].pos, heap[2 * ind + 1].pos))) {
    if (heap[2 * ind].pos < heap[2 * ind + 1].pos) {
      swap(heap[ind], heap[2 * ind]);
      ind = 2 * ind;
    }
    else {
      swap(heap[ind], heap[2 * ind + 1]);
      ind = 2 * ind + 1;
    }
  }
}

int main() {
  FILE *fin, *fout;
  int nr, op, x;
  int i;

  fin = fopen("heapuri.in", "r");

  fout = fopen("heapuri.out", "w");

  fscanf (fin, "%d", &nr);

  for (i = 0; i < nr; i++) {
    fscanf (fin, "%d", &op);
    if (op == 1) {
      fscanf (fin, "%d", &x);
      myAdd(x);
    } else if (op == 2) {
      fscanf (fin, "%d", &x);
      deleted[x] = 1;
    } else {
      while (deleted[heap[1].pos])
        myDelete(1);
      fprintf(fout, "%d\n", heap[1].val);
    }
  }

  fclose(fin);

  fclose(fout);

  return 0;
}