Cod sursa(job #2739014)

Utilizator andreiiorgulescuandrei iorgulescu andreiiorgulescu Data 6 aprilie 2021 18:03:15
Problema Heapuri Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.88 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 rmin;
    //cout << p << " " << h[p] << " " << v[h[p]] << endl;
    while (true)
    {
        if (2 * p > j or (v[h[2 * p]] >= v[h[p]] and v[h[2 * p + 1]] >= v[h[p]]))
        {
            //swap(poz[h[j]],poz[h[p]]);
            break;
        }
        else if (2*p + 1 <= j && v[h[2 * p]] >= v[h[2 * p + 1]])
            rmin = 2;
        else
            rmin = 1;
        //cout << v[h[2 * p]] << " " << v[h[2 * p + 1]] << '\n';
        if (rmin == 1)
        {
            swap(h[p],h[2 * p]);
            swap(poz[h[p]],poz[h[p * 2]]);
            p *= 2;
        }
        else
        {
            swap(h[p],h[2 * p + 1]);
            swap(poz[h[p]],poz[h[2 * p + 1]]);
            p = 2 * p + 1;
        }
    }
}

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;
}