Cod sursa(job #1849345)

Utilizator filip.mihalutMihalut Filip filip.mihalut Data 17 ianuarie 2017 12:46:40
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 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]),swap(poz[heap[pozz / 2]],poz[heap[pozz]]),muta_sus(pozz / 2);
}

void muta_jos(int pozz)
{
    if(2*pozz > nr)
        return;
    if(vec[heap[pozz]] > vec[heap[2*pozz]])
        swap(heap[pozz],heap[2*pozz]),swap(poz[heap[pozz * 2]],poz[heap[pozz]]),muta_sus(pozz * 2);
    else if(vec[heap[pozz]] > vec[heap[2*pozz + 1]])
        swap(heap[pozz * 2 + 1],heap[pozz]),swap(poz[heap[pozz * 2 + 1]],poz[heap[pozz]]),muta_sus(pozz * 2 + 1);
}

int main()
{
    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;
             swap(heap[nr],heap[poz[x]]);
             vec[x] = -1;
            // swap(poz[nr],poz[x]);
             nr--;
             if(vec[heap[x / 2]] > vec[heap[x]] && poz[x] > 1)
                muta_sus(poz[x]);
             else
                muta_jos(poz[x]);
             break;
        default:
            g << vec[heap[1]] << '\n';
            break;
        }
    }
    return 0;
}