Cod sursa(job #821898)

Utilizator UnforgivenMihai Catalin Botezatu Unforgiven Data 22 noiembrie 2012 19:31:51
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.54 kb
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#define MAX_size 200000

using namespace std;

typedef struct
{
    int nod;
    int crono;

}int_h;

int_h heap[MAX_size];
int vect[MAX_size];
int pozitii[MAX_size];

int size_heap = 0;
int size_vect_pozitii = 0;



void insert_in_heap(int x,int p)
{
    size_heap++;
    heap[size_heap].nod = x;
    heap[size_heap].crono = p;
    int poz = size_heap;
    while (poz > 1 && vect[heap[poz].nod] < vect[heap[poz/2].nod])
    {
        swap(heap[poz],heap[poz/2]);
        swap(pozitii[heap[poz].crono],pozitii[heap[poz/2].crono]);
        poz /= 2;
    }

}

void delete_from_heap(int x )
{
    swap(heap[size_heap],heap[x]);
    swap(pozitii[heap[size_heap].crono],pozitii[heap[x].crono]);
    size_heap--;
    int poz = size_heap;
    while ( poz > 1 || 2 * poz + 1  <= size_heap || 2 * poz <= size_heap )
    {
        int ok = 0 ;
        if (poz > 1 && vect[heap[poz].nod] < vect[heap[poz/2].nod] && ok == 0)
        {
             swap(heap[poz],heap[poz/2]);
             swap(pozitii[heap[poz].crono],pozitii[heap[poz/2].crono]);
             poz /= 2;
             ok = 1;
        }
        if (2 * poz + 1  <= size_heap  && vect[heap[poz].nod] > vect[heap[2*poz+1].nod] && ok == 0)
        {

            swap(heap[poz] , heap[2*poz+1]);
            swap(pozitii[heap[poz].crono],pozitii[heap[2*poz+1].crono]);
            poz = 2 * poz + 1;
            ok = 1;
        }
        if ( 2 * poz <= size_heap && vect[heap[poz].nod] > vect[heap[2 * poz].nod] && ok == 0)
        {
            swap(heap[poz] , heap[2 * poz]);
            swap(pozitii[heap[poz].crono],pozitii[heap[2*poz].crono]);
            poz *= 2;
            ok = 1;
        }
        if (ok == 0)
        {
            break;
        }
    }
}

int main()
{

    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    int nr_op;
    scanf("%d",&nr_op);
    int l = 0;
    for (int i=0;i<nr_op;i++)
    {
        int x,y;
        scanf("%d",&x);
        if (x == 1)
        {
            scanf("%d",&y);
            size_vect_pozitii++;
            vect[size_vect_pozitii] = y;
            l++;
            pozitii[l] = size_heap+1;

            insert_in_heap(size_vect_pozitii,l);
        }
        if (x == 2)
        {
            scanf("%d",&y);
            delete_from_heap(pozitii[y]);
            l--;
        }
        if (x == 3)
        {
            printf("%d\n",vect[heap[1].nod]);
        }
    }

    return 0;
}