Cod sursa(job #2747119)

Utilizator DenisTroacaDenis Troaca DenisTroaca Data 28 aprilie 2021 20:38:37
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.81 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
vector<int> v;
int indice(int val)
{
    for (int i = 0; i < v.size(); i++)
        if (val == v[i])
            return i;
    return 0;
}
 
void urca(int poz)
{
    while (poz)
    {
        int tata = (poz - 1) / 2;
        if (v[tata] < v[poz])
        {   
            swap(v[tata], v[poz]);
            poz = tata;
        }
        else
        {
            break;
        }
    }
}
 
void coboara(int poz)
{
    if (poz * 2 + 1 >= v.size())
        return;
    int fiu_st = v[poz * 2 + 1];
    if ((poz * 2 + 2 == v.size()) || fiu_st > v[poz * 2 + 2])
    {
        if (fiu_st > v[poz])
        {
            swap(v[poz], v[poz * 2 + 1]);
            coboara(poz * 2 + 1);
            return;
        }
        else
        {
            return;
        }
    }
    else
    {
        if (v[poz * 2 + 2] > v[poz])
        {
            swap(v[poz], v[poz * 2 + 2]);
            coboara(poz * 2 + 2);
            return;
        }
        else
        {
            return;
        }
    }
}
vector <int>aux;
int n, x, t, nr, k;
int main()
{
    fin >> n;
    for (int i = 0; i < n; i++)
    {
        fin >> t;
        if (t == 1)
        {
            fin >> x;
            nr++;
            aux.push_back(-x);
            v.push_back(-x);
            push_heap(v.begin(), v.end());
        }
        if (t == 2)
        {
            fin >> x;
            k = indice(aux[x-1]);
            swap(v[k], v[v.size() - 1]);
            v.pop_back();
            coboara(k);
            urca(k);
        }
        if (t == 3)
        {
            fout << -v.front() << '\n';
        }
    }
}