Cod sursa(job #1850174)

Utilizator filip.mihalutMihalut Filip filip.mihalut Data 18 ianuarie 2017 12:00:03
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include <iostream>
#include <fstream>
#define dim 200005
using namespace std;

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

int vec[dim],lung,heap[dim],poz[dim],nr;

void muta_sus(int x)
{
    while (x / 2 && vec[heap[x]] < vec[heap[x / 2]])
    {
        swap(heap[x], heap[x/2]);
        poz[heap[x]] = x;
        poz[heap[x/2]] = x / 2;
        x /= 2;
    }
}

void muta_jos(int pozz)
{
    int x;
    while(x != pozz)
    {
        x = pozz;
        if(2*pozz <= lung && vec[heap[pozz]] > vec[heap[2*pozz]])
            pozz *= 2;
        if(2*x + 1 <= lung && vec[heap[pozz]] > vec[heap[2*x + 1]])
             pozz = x * 2 + 1;

        swap(heap[pozz],heap[x]);
        poz[heap[pozz]] = pozz;
        poz[heap[x]] = x;
    }
}

int main()
{
    int n,caz,x;
    f >> n;
    while(n)
    {
        f >> caz;
        switch(caz)
        {
        case 1:
            f >> x;
            vec[++nr] = x;
            heap[++lung] = nr;
            poz[nr] = lung;
            muta_sus(lung);
            break;
        case 2:
            f >> x;
            vec[x] = -1;
            muta_sus(poz[x]);
            poz[heap[1]] = 0;
            swap(heap[1],heap[lung]);
            lung--;
            poz[heap[1]] = 1;
            if(lung > 1)
                muta_jos(1);
            break;
        default:
            g << vec[heap[1]] << '\n';
            break;
        }
        n--;
    }
    return 0;
}