Cod sursa(job #2294024)

Utilizator dragos99Homner Dragos dragos99 Data 1 decembrie 2018 20:19:34
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.98 kb
#include<fstream>
#include<vector>
#include<iostream>
#include<stdlib.h>
#include<stdio.h>

using namespace std;

int n;
int heap[200001], pos[200001], ordine[200001];
int length = 0;
int up_position;

inline int father(int x){
    return x / 2;
}

inline int left_son(int x){
    return x * 2;
}

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

void heap_up(int x){
    int x_init = x;
    int val = heap[x];
    int val_ordine = ordine[x];

    while( x > 1 && val < heap[father(x)]){
        swap(heap[x], heap[father(x)]);

        ordine[heap[x]] = x;
        ordine[heap[x/2]] = x / 2;
        x = father(x);
    }

    up_position = x;
}

void heap_down(int x){
    int son = 1;
    int x_init = x;
    while(son){
        son = 0;
        if(left_son(x) <= length){
            son = left_son(x);
            if(right_son(x) <= length && heap[right_son(x)] < heap[left_son(x)]){
                son = right_son(x);
            }

            if(heap[son] >= heap[x])
                son = 0;
        }

        if(son){
            swap(heap[son], heap[x]);
            ordine[heap[x]] = x;
            ordine[heap[son]] = son;

            x = son;
        }

    }
}

int find_position(int x){
    for(int i = 1 ; i <= length ; i++)
        if(heap[i] == x)
            return i;
}

int main()
{

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

int operatie;
int x, k = 0;

scanf("%d", &n);
for(int i = 0 ; i < n ; i++){
    scanf("%d", &operatie);
    if(operatie == 1){
        scanf("%d", &x);

        heap[++length] = x;
        ordine[++k] = length;

        heap_up(length);
    }
    if(operatie == 2){
        scanf("%d", &x);

        int position = ordine[x];

        swap(heap[length], heap[position]);
        length --;

        heap_up(position);
        heap_down(up_position);
    }
    if(operatie == 3){
        printf("%d\n", heap[1]);
    }
}

return 0;
}