Cod sursa(job #2893678)

Utilizator mirceaspPetcu Mircea mirceasp Data 26 aprilie 2022 15:31:53
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.22 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
long long heap[200001],aux[200001],pozitii[200001];
long long k = 0;
void urca(long long poz)
{
    while (poz)
    {
        if(heap[(poz-1)/2]>heap[poz])
        {
            swap(pozitii[aux[heap[(poz-1)/2]]],pozitii[aux[heap[poz]]]);
            swap(aux[heap[(poz-1)/2]],aux[heap[poz]]);
            swap(heap[(poz-1)/2],heap[poz]);
            poz = (poz-1)/2;
        } else
            break;
    }
}
void coboara(long long poz) {
    if (poz * 2 + 1 > k)
        return;
    long long fiu_st = heap[poz * 2 + 1];
    if ((poz * 2 + 2 == k+1) || fiu_st < heap[poz * 2 + 2]) {
        if (fiu_st < heap[poz]) {
            swap(pozitii[aux[heap[poz*2+1]]],pozitii[aux[heap[poz]]]);
            swap(aux[heap[poz*2+1]],aux[heap[poz]]);
            swap(heap[poz], heap[poz * 2 + 1]);
            coboara(poz * 2 + 1);
            return;
        } else {
            return;
        }
    } else {
        if (heap[poz * 2 + 2] < heap[poz]) {
            swap(pozitii[aux[heap[poz*2+2]]],pozitii[aux[heap[poz]]]);
            swap(aux[heap[poz*2+2]],aux[heap[poz]]);
            swap(heap[poz], heap[poz * 2 + 2]);
            coboara(poz * 2 + 2);
            return;
        } else {
            return;
        }
    }
}
int main()
{
    long long n,op,nr,poz,i;
    long long introdus = 1;
    ifstream f("heapuri.in");
    ofstream g("heapuri.out");
    f>>n;
    for(i = 1;i<=n;i++)
    {

        f>>op;
        if(op == 1)
        {
            f>>nr;
            pozitii[introdus] = k;
            ///tin minte pe pozitia introdusa ce pozitie are in heap
            aux[nr] = introdus;
            /// tin minte ca un vector de frecv pe poz valoare din heap al catelea a fost introdus
            heap[k] = nr;
            ///heap-ul efectiv
            urca(k);
            introdus++;
            k++;

        }
        else if(op == 2)
        {
            f>>poz;
            heap[pozitii[poz]] = heap[k-1];
            k--;
            urca(pozitii[poz]);
            coboara(pozitii[poz]);
        } else
            g<<heap[0]<<'\n';
    }
    f.close();
    g.close();
    return 0;
}