Cod sursa(job #1849516)

Utilizator filip.mihalutMihalut Filip filip.mihalut Data 17 ianuarie 2017 17:20:59
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <iostream>
#include <fstream>
#define dim 200005

using namespace std;

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

int heap[dim],poz[dim],vec[dim],n,i,caz,x,nr,lung;

void muta_sus(int pozz)
{
    if(pozz == 1)
        return;
    if(vec[heap[pozz / 2]] > vec[heap[pozz]])
        swap(heap[pozz / 2],heap[pozz]),poz[heap[pozz / 2]] = pozz / 2,poz[heap[pozz]] = pozz,muta_sus(pozz / 2);
}

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

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

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