Cod sursa(job #1751815)

Utilizator daymon_cDumitru Chitoraga daymon_c Data 1 septembrie 2016 22:59:19
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.89 kb
#include <stdio.h>
#include<algorithm>
#define NMAX 200005 
using namespace std;

int H[NMAX], n, m, logger[NMAX], pos[NMAX], l;

int left(int x)
{
    return x*2;
}

int right(int x)
{
    return x*2+1;
}

void shift(int H[], int N, int father)
{
    int son;
    do
    {
        son = 0;
        if(left(father) <=N)
        {
            son = left(father);
            if(right(father) <=N 
                && logger[H[right(father)]] < logger[H[left(father)]])
                    son = right(father);
            if(logger[H[son]] > logger[H[father]])
                son = 0;
        }
        if (son)
        {
            swap(H[son], H[father]);
            swap(pos[H[son]], pos[H[father]]);
            father = son;
        }
        
    } while(son);
}

void boost(int H[], int N, int son)
{
    int father = son>>1;

    while (father && logger[H[father]] > logger[H[son]])
    {
        swap(H[father], H[son]);
        swap(pos[H[son]], pos[H[father]]);

        son = father;
        father = son>>1;
    }
}

void cut(int H[], int &N, int elem)
{
    H[pos[elem]] = H[N--];
    boost(H, N, pos[elem]);
    shift(H, N, pos[elem]);
}

void insert(int H[], int &N, int elem)
{
    H[++N] = elem;
    boost(H, N, pos[elem]);
}

void heap(int H[], int N)
{
    for(int i=N/2; i; --i)
        shift(H, N, i);
}

int main()
{
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);

    scanf("%d", &m);

    int o,v;
    for(int i=0; i<m; ++i)
    {
        scanf("%d", &o);
        switch(o)
        {
            case 1:
                scanf("%d", &v);
                logger[++l] = v;
                pos[l] = n + 1;
                insert(H, n, l);
            break;
            case 2:
                scanf("%d", &v);
                cut(H, n, v);
            break;
            case 3:
                printf("%d\n", logger[H[1]]);
            break;
        }
    }

    return 0;
}