Cod sursa(job #3199170)

Utilizator Remus.RughinisRemus Rughinis Remus.Rughinis Data 31 ianuarie 2024 21:53:52
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <iostream>
#include <fstream>
#define MAXN 200000
#define P(x) (x-1)/2
#define C1(x) x*2+1
#define C2(x) x*2+2

#define DEBUG 0

using namespace std;

struct HeapElement {
  int x, id;

public:
  bool operator< (const HeapElement other){
    return this->x < other.x;
  }
  bool operator<= (const HeapElement other){
    return this->x <= other.x;
  }
};
HeapElement h[MAXN];
int dr = 0;

bool exists(int x){
  return x < dr;
}

void upHeap(int x){
  if(x == 0)
    return;

  int p = P(x);
  if(h[x] < h[p])
    swap(h[p], h[x]);
  upHeap(p);
}

void downHeap(int x){
  int min;
  if(!exists(C1(x)) && !exists(C2(x)) || !exists(x)) 
    return;

  if(!exists(C1(x)))
    min = C2(x);
  else if(!exists(C1(x)))
    min = C1(x);

  else if(h[C2(x)] <= h[C1(x)])
    min = C2(x);
  else 
    min = C1(x);

  if(h[min] < h[x])
    swap(h[min], h[x]);
  downHeap(min);
}

void add(int val, int nr){
  h[dr].x = val;
  h[dr].id = nr;
  dr ++;
  upHeap(dr - 1);
}
void remove(int id){
  if(dr == 0)
    return;

  h[id] = h[dr - 1];
  dr --;
  downHeap(id);
}

int main(){
  int n, nr = 1;

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

  for(int i = 0; i < n; i ++){
    int op;
    fin >> op;

    if(op == 1){
      int x;
      fin >> x;
      add(x, nr);
      nr ++;
    
    } else if(op == 2){
      int j = 0, x;
      fin >> x;
      while(h[j].id != x)
        j ++;
      remove(j);

    } else
      fout << h[0].x << "\n";

    if(DEBUG){
      for(int j = 0; j < dr; j ++)
        printf("%d ", h[j].x);
      printf("\n");
    }
  }
  fin.close();
  fout.close();

  return 0;
}