Cod sursa(job #2808124)

Utilizator victorzarzuZarzu Victor victorzarzu Data 24 noiembrie 2021 17:10:52
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.99 kb
#include <bits/stdc++.h>
#define n_max 100000

using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
int n, x, y;

void insert_heap(pair<int, int> *heap, int position)
{
  if(position == 1)
    return;
  int parent = position / 2;
  
  if(heap[parent].first > heap[position].first)
    {
      swap(heap[parent], heap[position]);
      insert_heap(heap, parent);
    }
}

void find_in_heap(pair<int, int> *heap, int position, int value, int heap_size, int *result)
{
  if(*result != -1)
    return;

  if(heap[position].second == value)
    {
      *result = position; 
      return;
    }

  int left = 2 * position;
  int right = 2 * position + 1;
  
  find_in_heap(heap, left, value, heap_size, result);
  find_in_heap(heap, right, value, heap_size, result);
}

void update_heap(pair<int, int> *heap, int position, int heap_size)
{
  int left = 2 * position;
  int right = 2 * position + 1;
  int smallest = position;

  if(left <= heap_size && heap[smallest].first > heap[left].first)
    smallest = left;
  if(right <= heap_size && heap[smallest].first > heap[right].first)
    smallest = right;
  
  if(smallest != position)
    {
      swap(heap[smallest], heap[position]);
      update_heap(heap, smallest, heap_size);
    }
}

void read()
{
  f>>n;
  pair<int, int> *heap = new pair<int, int>[n + 1];
  int heap_size = 0;
  int number = 0;
  for(int i = 1;i <= n;++i)
    {
      f>>x;
      if(x == 1)
        {
          ++number;
          f>>y;
          heap[++heap_size] = make_pair(y, number);
          insert_heap(heap, heap_size);
        }
      else if(x == 2)
        {
          f>>y;

          int result = -1;
          find_in_heap(heap, 1, y, heap_size, &result);
          swap(heap[result], heap[heap_size]);
          --heap_size;
          update_heap(heap, result, heap_size);
        }
      else
       g<<heap[1].first<<'\n'; 

    }

  delete heap;
}

int main()
{
  read();
  return 0;
}