Cod sursa(job #2894919)

Utilizator TindecheTindeche Alexandru Tindeche Data 28 aprilie 2022 16:24:26
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.92 kb
#include <string.h>
#include <fstream>
#include <vector>
#include <algorithm>
#include <iostream>

using namespace std;

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

vector <pair<int, int>> heap;
int n;

void heapify(int i)
{
    int mn = i; // Presupunem ca minimul este radacina
    int st = 2 * i + 1; // Pozitia nodului din stanga lui
    int dr = 2 * i + 2; // Pozitia nodului din dreapta lui

    // Vedem care nod este mai mic:
    if(st < heap.size() && heap[st].second < heap[mn].second)
        mn = st;
    if(dr < heap.size() && heap[dr].second < heap[mn].second)
        mn = dr;

    // Daca varful nu este minim facem swap si heapify la subarbore
    if(mn != i)
    {
        swap(heap[i], heap[mn]);
        heapify(mn);
    }
}

void build_heap(int i)
{
    int parinte = (i - 1) / 2; // Gasim parintele
    if(heap[i].second < heap[parinte].second)
    {
        swap(heap[i], heap[parinte]);
        build_heap(parinte);
    }
}

void sterge(int p)
{
    pair<int, int> u = heap[heap.size() - 1]; // Ultimul nod

    // Gasim pe ce pozitie se afla elementul intrat al i-lea
    int poz;
    for(int i = 0; i < heap.size(); i++)
        if(heap[i].first == p)
            poz = i;

    // Facem swap intre elementul de sters si ultimul element
    heap[poz] = u;
    heap.pop_back();
    heapify(poz);
}

int main ()
{
    int k = 0;
    fin >> n;
    for(int i = 0; i < n; i++)
    {
        int opt, nr;
        fin >> opt;
        switch(opt)
        {
            case 1:
            {
                fin >> nr;
                heap.push_back(make_pair(k++, nr));
                build_heap(heap.size() - 1);
                break;
            }
            case 2:
            {
                fin >> nr;
                sterge(nr - 1);
                break;
            }
            case 3:
            {
                fout << heap[0].second << '\n';
                break;
            }
        }
    }
    return 0;
}