Cod sursa(job #2605410)

Utilizator daniel.stefanStoica Daniel daniel.stefan Data 24 aprilie 2020 21:14:35
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.65 kb
#include <iostream>
#include <fstream>
#include <assert.h>

using namespace std;
ifstream fin ("heapuri.in");
ofstream fout ("heapuri.out");

const int MAX_HEAP_SIZE = 200010;
int heap[MAX_HEAP_SIZE], pos[MAX_HEAP_SIZE], track_insert[MAX_HEAP_SIZE];

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

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

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

void up(int index){
    bool flag = true;

    while(flag){
        if(index == 1 || heap[index] > heap[father(index)]){
            flag = false;
        }
        else{
            swap(pos[heap[index]], pos[heap[father(index)]]);
            swap(heap[index], heap[father(index)]);
            index = father(index);
        }
    }
}

void down(int index, int nr_elem){

    int son;

    do{
        son = 0;

        if(left_son(index) <= nr_elem){
            son = left_son(index);

            if(right_son(index) <= nr_elem && heap[right_son(index)] < heap[left_son(index)])
                son = right_son(index);
            if(heap[son] >= heap[index])
                son = 0;
        }

        if(son){
            swap(pos[son],pos[index]);
            swap(heap[index], heap[son]);
            index = son;
        }

    }while(son);

}


void insert_element(int insert_elem, int nr_elem){
    int index = nr_elem;

    heap[index] = insert_elem;

    up(index);
}

void delete_element(int delete_elem, int nr_elem){
    int del = track_insert[delete_elem];

    heap[pos[del]] = heap[nr_elem];
    pos[heap[pos[del]]] = pos[del];
    nr_elem--;

    int position = pos[del];

    if(position > 1  && heap[position] < heap[father(position)])
        up(position);
    else
        down(position, nr_elem);
}


int main()
{
    int N, nr_elem = 0, i = 1, counter, track, insert_elem, delete_elem;
    fin >> N;

    assert(1 <= N && N <= 200000);

    for(counter = 1; counter <= N; counter++){
        fin >> track;

        assert(1 <= track && track <= 3);

        if(track == 1){
            fin >> insert_elem;
            assert(1 <= insert_elem && insert_elem <= 1000000000);
            nr_elem++;
            pos[insert_elem] = i;
            track_insert[i++] = insert_elem;
            insert_element(insert_elem, nr_elem);
        }
        else if (track == 2){
            fin >> delete_elem;
            assert(1 <= delete_elem && delete_elem <= 1000000000);
            delete_element(delete_elem, nr_elem);
        }
        else{
            fout << heap[1] <<"\n";
        }
    }

    return 0;
}