Cod sursa(job #2672947)

Utilizator vladm98Munteanu Vlad vladm98 Data 15 noiembrie 2020 15:19:21
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.25 kb
#include <bits/stdc++.h>

using namespace std;

struct Node {
    int value, index;
};

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
vector <Node> heap;
int whereheap[200010];

void swapNode(int pos1, int pos2) {
    swap(heap[pos1], heap[pos2]);
    swap(whereheap[heap[pos1].index], whereheap[heap[pos2].index]);
}

void insert(Node node)
{
    heap.push_back(node);
    whereheap[node.index] = heap.size() - 1;
    int currentPosition = heap.size() - 1;

    while(currentPosition != 1 and heap[currentPosition].value < heap[currentPosition / 2].value) {
        swapNode(currentPosition, currentPosition / 2);
        currentPosition /= 2;
    }
}

void del(int index)
{
    int currentPosition = whereheap[index];
    swapNode(currentPosition, heap.size() - 1);
    heap.pop_back();

    while(currentPosition != 1 and heap[currentPosition].value < heap[currentPosition / 2].value) {
        swapNode(currentPosition, currentPosition / 2);
        currentPosition /= 2;
    }

    while (2 * currentPosition < heap.size()) {
        if (2 * currentPosition + 1 >= heap.size() or heap[2 * currentPosition].value < heap[2 * currentPosition + 1].value) {
            if (heap[currentPosition].value > heap[2 * currentPosition].value) {
                swapNode(currentPosition, 2 * currentPosition);
                currentPosition *= 2;
            } else {
                break;
            }
        } else {
            if (heap[currentPosition].value > heap[2 * currentPosition + 1].value) {
                swapNode(currentPosition, 2 * currentPosition + 1);
                currentPosition *= 2;
                currentPosition += 1;
            } else {
                break;
            }
        }
    }
}
int main() {
    Node useless;
    heap.push_back(useless);
    int n, cnt = 0;
    fin >> n;
    while(n--)
    {
        int op;
        fin >> op;
        if(op == 1)
        {
            int x;
            fin >> x;
            cnt += 1;
            Node node;
            node.index = cnt;
            node.value = x;
            insert(node);
        }
        if(op == 2)
        {
            int x;
            fin >> x;
            del(x);
        }
        if(op == 3)
        {
            cout << heap[1].value << "\n";
        }
    }
    return 0;
}