Cod sursa(job #1751782)

Utilizator daymon_cDumitru Chitoraga daymon_c Data 1 septembrie 2016 22:20:13
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.85 kb
#include <stdio.h>
#include<algorithm>
#define NMAX 200005

using namespace std;

int H[NMAX], n, m, log[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 
                && log[H[right(father)]] < log[H[left(father)]])
                    son = right(father);
            if(log[H[son]] > log[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 && log[H[father]] > log[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[elem] = H[N--];
    boost(H, N, elem);
    shift(H, N, elem);
}

void insert(int H[], int &N, int elem)
{
    H[++N] = elem;
    boost(H, N, 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);
                log[++l] = v;
                pos[l] = n + 1;
                insert(H, n, l);
            break;
            case 2:
                scanf("%d", &v);
                cut(H, n, pos[v]);
            break;
            case 3:
                printf("%d\n", log[H[1]]);
            break;
        }
    }

    return 0;
}