Cod sursa(job #2758019)

Utilizator lahayonTester lahayon Data 8 iunie 2021 01:55:59
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.36 kb
#include <fstream>
#include <vector>

using namespace std;

const int MAX_N  = 1 << 18;

vector<int> heap, elements, pos;

int father(int position){

    return (position - 1) / 2;
}

int left_son(int position){

    return position * 2 + 1;
}

int right_son(int position){

    return position * 2 + 2;
}

void sift_up(int position){

    int init = heap[position];

    while(position > 0 && elements[init] < elements[heap[father(position)]]){
        pos[heap[father(position)]] = position;
        heap[position] = heap[father(position)];
        position = father(position);
    }
    pos[init] = position;
    heap[position] = init;
}

void sift_down(int position){

 
    int son = -1;

    while(son){

        son = 0;

        if(left_son(position) < heap.size()){
                son = left_son(position);
                if(right_son(position) < heap.size() && elements[heap[right_son(position)]] <  elements[heap[left_son(position)]])
                    son = right_son(position);
                if(elements[heap[son]] >= elements[heap[position]])
                    son = 0;
        }
        if(son){
            pos[heap[position]] = pos[heap[position]] + pos[heap[son]] - (pos[heap[son]] = pos[heap[position]]);
            heap[position] = heap[position] + heap[son] - (heap[son] = heap[position]);
            position = son;
            } 
    }
}

int main(){    

    ifstream cin("heapuri.in");
    ofstream cout("heapuri.out");

    int N, op, val;
    cin >> N;
    
    for(; N > 0; --N){

        cin >> op;
        switch(op){
            case 1:
                cin >> val;
                elements.push_back(val);
                pos.push_back(elements.size() - 1);
                heap.push_back(elements.size() - 1);
                sift_up(heap.size() - 1);
                break;
            case 2:
                cin >> val; --val;
                heap[pos[val]] = heap[heap.size() - 1];
                pos[heap[heap.size() - 1]] = pos[val];
                sift_down(pos[val]);
                pos[val] = -1;
                heap.pop_back();
                break;
            case 3:
                cout << elements[heap[0]] << "\n";
                break;
            default:
                break;
        }
    }

    cin.close();
    cout.close();

  return 0;
	
}