Cod sursa(job #3289980)

Utilizator MMEnisEnis Mutlu MMEnis Data 29 martie 2025 11:28:26
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.88 kb
#include <iostream>
#include <fstream>
#include <algorithm>

using namespace std;

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

struct cel
{
    int val, poz;
}heap[200001];

int chrono[200001];
int n, nr;

void aux ( cel &a, cel &b )
{
    cel auxi = a;
    a = b;
    b = auxi;
}

void push( int nod )
{
    if ( nod > 1 && heap[nod].val < heap[nod / 2].val )
    {
        chrono[heap[nod].poz] = nod / 2;
        chrono[heap[nod / 2].poz] = nod;
        aux ( heap[nod], heap[nod / 2] );
        push ( nod / 2 );
    }
}

void pull ( int nod )
{
    if ( nod * 2 <= n && ( heap[nod].val > heap[nod * 2].val || heap[nod].val > heap[nod * 2 + 1].val ) )
    {
        int cnt = 1;
        if ( nod * 2 + 1 > n || heap[nod * 2].val < heap[nod * 2 + 1].val )
            cnt = 0;
        chrono[heap[nod].poz] = nod * 2 + cnt;
        chrono[heap[nod * 2 + cnt].poz] = nod;
        aux ( heap[nod], heap[nod * 2 + cnt] );
        pull ( nod * 2 + cnt );
    }
}

void afisare()
{
    int k = 1;
    for ( int i = 1; i <= n; i ++ )
    {
        cout << heap[i].val << " ";
        if ( ( i + 1 ) % k == 0 )
        {
            cout << endl;
            k *= 2;
        }
    }
    cout << endl << endl;
}

int main()
{
    int q;
    f >> q;
    while ( q -- )
    {
        int c, x;
        f >> c;
        if ( c == 1 )
        {
            f >> x;
            nr ++;
            n ++;
            heap[n].val = x;
            heap[n].poz = nr;
            chrono[nr] = n;
            push(n);
        }
        else if ( c == 2 )
        {
            f >> x;
            aux ( heap[chrono[x]], heap[n] );
            heap[n].val = 0;
            n --;
            pull ( chrono[x] );
            push ( chrono[x] );
        }
        else g << heap[1].val << '\n';
        //afisare();
    }
    return 0;
}