Cod sursa(job #3266052)

Utilizator happyplaneDragos Miu-Baldu happyplane Data 5 ianuarie 2025 15:24:48
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

const int NMax = 200002;
int Heap[NMax], Ord[NMax], PosVec[NMax], NrElem = 0, HeapSize = 0;

void AddHeap(int Val)
{
  Heap[++HeapSize] = Val;
  PosVec[Val] = HeapSize;
  int i = HeapSize;
  while (i > 1 && Ord[Heap[i]] < Ord[Heap[i / 2]])
  {
    swap(Heap[i], Heap[i / 2]);
    PosVec[Heap[i]] = i;
    PosVec[Heap[i / 2]] = i / 2;
    i /= 2;
  }
}

void DelHeap(int NthElem)
{
  int pos = PosVec[NthElem];
  if (pos == 0)
    return;
  swap(Heap[pos], Heap[HeapSize--]);
  PosVec[Heap[pos]] = pos;
  PosVec[NthElem] = 0;
  int i = pos;
  while (true) {
    int smallest = i;
    if (2 * i <= HeapSize && Ord[Heap[2 * i]] < Ord[Heap[smallest]]) {
      smallest = 2 * i;
    }
    if (2 * i + 1 <= HeapSize && Ord[Heap[2 * i + 1]] < Ord[Heap[smallest]]) {
      smallest = 2 * i + 1;
    }
    if (smallest != i) {
      swap(Heap[i], Heap[smallest]);
      PosVec[Heap[i]] = i;
      PosVec[Heap[smallest]] = smallest;
      i = smallest;
    }
    else {
      break;
    }
  }
}

int main()
{
  int NrIsnt;
  fin >> NrIsnt;
  for (int i = 0;i < NrIsnt;++i)
  {
    int Comm;
    fin >> Comm;
    switch (Comm)
    {
    case 2:
      int NthElem;
      fin >> NthElem;
      DelHeap(NthElem);
      break;
    case 3:
      fout << Ord[Heap[1]] << "\n";
      break;
    default:
      int Val;
      fin >> Val;
      Ord[++NrElem] = Val;
      AddHeap(NrElem);
    }
  }
  fin.close();
  fout.close();
  return 0;
}