Cod sursa(job #2739019)

Utilizator andreiiorgulescuandrei iorgulescu andreiiorgulescu Data 6 aprilie 2021 18:09:17
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <bits/stdc++.h>

using namespace std;

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

int h[200005],v[200005],poz[200005],j;

void upheap(int p)
{
    while (v[h[p]] < v[h[p / 2]] and p > 1)
    {
        swap(h[p],h[p / 2]);
        swap(poz[h[p]],poz[h[p / 2]]);
        p /= 2;
    }
}

void downheap(int p)
{
    int fs = 2 * p,fd = 2 * p + 1,bun = p;
    //out<<h[fs]<<" "<<h[fd]<<" "<<h[bun]<<endl;
    if(fs <= j && v[h[fs]] < v[h[bun]])
        bun = fs;
    if(fd <= j && v[h[fd]] < v[h[bun]])
        bun = fd;
    if(bun != p)
    {
        //swapp(p,bun);
        swap(h[p],h[bun]);
        poz[h[p]] = p;
        poz[h[bun]] = bun;
        downheap(bun);
    }
}

int main()
{
    int n,i,x,y,p = 0;
    in >> n;
    for (i = 1; i <= n; i++)
    {
        in >> x;
        if (x == 3)
            out << v[h[1]] << '\n';
        else if (x == 1)
        {
            in >> y;
            v[++p] = y;
            h[++j] = p;
            poz[p] = j;
            upheap(j);
        }
        else
        {
            in >> y;
            swap(h[j],h[poz[y]]);
            j--;
            downheap(poz[y]);
        }
        /*for (int q = 1; q <= j; q++)
            cout << v[h[q]] << " ";
        cout << endl;
        for (int q = 1; q <= j; q++)
            cout << h[q] << " ";
        cout << endl;
        for (int q = 1; q <= p; q++)
            cout << poz[q] << " ";
        cout << endl << endl;*/
    }
    return 0;
}