Cod sursa(job #2293832)

Utilizator dragos99Homner Dragos dragos99 Data 1 decembrie 2018 17:06:26
Problema Heapuri Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.94 kb
#include<fstream>
#include<vector>
using namespace std;
    ifstream f("heapuri.in");
    ofstream g("heapuri.out");
int n;
int heap[200001], pos[200001];
int length = 0;

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 poz_x){
    while(heap[poz_x] < heap[father(poz_x)] ){
        swap(heap[poz_x], heap[father(poz_x)]);
        poz_x = father(poz_x);
    }
}

void heap_down(int poz_x){
    bool correct_position = false;
    while(correct_position == false){
        int minn = min(heap[left_son(poz_x)], heap[right_son(poz_x)]);
        correct_position = true;
        if(left_son(poz_x) <= length){
            if(heap[left_son(poz_x)] < heap[poz_x] && minn == heap[left_son(poz_x)]){
                swap(heap[left_son(poz_x)] , heap[poz_x]);
                poz_x = left_son(poz_x);
                correct_position = false;
            }
        }

        if(right_son(poz_x) <= length){
            if(heap[right_son(poz_x)] < heap[poz_x] && minn == heap[right_son(poz_x)]){
                swap(heap[right_son(poz_x)], poz_x);
                poz_x = right_son(poz_x);
                correct_position = false;
            }
        }
    }
}

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

int main()
{

int operatie;
int x, k = 0;

f>>n;
for(int i = 0 ; i < n ; i++){
    f>>operatie;
    if(operatie == 1){
        f>>x;
        pos[k++] = x;
        heap[++length] = x;
        heap_up(length);
    }
    if(operatie == 2){
        f>>x;
        int position = find_position(pos[x - 1]);
        swap(heap[length], heap[position]);
        length -- ;
        heap_down(position);
        heap_up(position);
    }
    if(operatie == 3){
        g<<heap[1]<<'\n';
    }
}

return 0;
}