Cod sursa(job #3126336)

Utilizator CybotXDStancila Ionut CybotXD Data 6 mai 2023 15:47:03
Problema Heapuri cu reuniune Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.87 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

ifstream f("mergeheap.in");
ofstream g("mergeheap.out");


int n, x, m, q;

class Heap{
private:
    int _size=0;
    vector<int> v;

public:

    void shiftUp(int index);
    void shiftDown(int index);
    int popMax();
    void MergeHeap(Heap &other);
    void HeapInsert(int value);
    void ClearHeap();

    int parent(int index){ return (index-1)/ 2; }
    int left(int index){ return (2*index+1); }
    int right(int index){ return (2*index+2); }
};

void Heap::shiftUp(int index)
{ if (index > _size) return;
  if (index == 0) return;
  if(v[index]>v[parent(index)])
    swap(v[index], v[parent(index)]);

  shiftUp(parent(index));

}

void Heap::HeapInsert(int value)
{ _size++;
  int index=_size-1;
  v.push_back(value);
  shiftUp(index);
}

void Heap::shiftDown(int index)
{ int swapID=index;

  if (left(index)<=_size && v[index] < v[left(index)])
    swapID=left(index);
  
  if (right(index)<=_size && v[swapID] < v[right(index)])
    swapID=right(index);

  if (swapID!=index)
  { swap(v[index], v[swapID]);
    shiftDown(swapID);
  }

  return;
}

int Heap::popMax()
{
  if (_size == 0)
    return -1;

  int max_val = v[0];
  v[0] = v[_size - 1];
  v.pop_back();
  _size--;

  shiftDown(0);

  return max_val;
}


void Heap::MergeHeap(Heap& other)
{
  for (int i = 0; i < other._size; i++)
    HeapInsert(other.v[i]);
  
  other.v.clear();
  other._size = 0;
}


int main()
{
    f>>n>>q;
    Heap h[n+1];
    int op=0;
    while(q)
    { f>>op;
      if (op==1)
      { f>>m>>x;
        h[m].HeapInsert(x);
      }
      else if (op==2)
      { f>>m;
        g<<h[m].popMax()<<'\n';
      }
      else
      { int m1, m2;
        f>>m1>>m2;
        h[m1].MergeHeap(h[m2]);
      }
      q--;
    }
}