Cod sursa(job #1752370)

Utilizator daymon_cDumitru Chitoraga daymon_c Data 3 septembrie 2016 17:21:49
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 2.37 kb
#include <stdio.h>
#include<algorithm>
#define NMAX 105
using namespace std;

int h[NMAX]; // H[] - stores values by their read order
int heapSize, inputSize, values[NMAX];
int positions[NMAX]; // positions[i] = the position of the i-th value in the heap
int curValueNumber;

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

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

// father = index in H, H[father] returns the read order
void shift(int H[], int N, int father)
{
    int son;
    do
    {
        son = 0;
        if(left(father) <= N)
        {
            son = left(father);
            if(right(father) <=N
                && values[H[right(father)]] < values[H[left(father)]])
                    son = right(father);
            if(values[H[son]] >= values[H[father]])
                son = 0;
        }
        if (son)
        {
            swap(H[son], H[father]);
            swap(positions[H[son]], positions[H[father]]);
            father = son;
        }

    } while(son);
}

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

    while (father && values[H[father]] > values[H[son]])
    {
        swap(H[father], H[son]);
        swap(positions[H[son]], positions[H[father]]);

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

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

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

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

    scanf("%d", &inputSize);

    int o,v;
    for(int i=0; i<inputSize; ++i)
    {
        scanf("%d", &o);

        int tempo;
        switch(o)
        {
            case 1:
                scanf("%d", &v);
                        if (v == 12) {
                            v = 12;
                        }
                values[++curValueNumber] = v;
                positions[curValueNumber] = heapSize + 1;
                insert(h, heapSize, curValueNumber);
            break;
            case 2:
                scanf("%d", &v);
                tempo = positions[v];
                swap(positions[v], positions[h[heapSize]]);
                positions[v] = 0;
                cut(h, heapSize, tempo);
            break;
            case 3:
                printf("%d\n", values[h[1]]);
            break;
        }
    }

    return 0;
}