Cod sursa(job #3124327)

Utilizator mex7Alexandru Valentin mex7 Data 27 aprilie 2023 20:49:56
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.92 kb
#include <bits/stdc++.h>
#define ll long long
#define cin fin
#define cout fout
using namespace std;

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

pair <int, int> heap[200005];
int length, v[200005];

void swapEl(int index1, int index2) {
    v[heap[index1].second] = index2;
    v[heap[index2].second] = index1;
    swap(heap[index1], heap[index2]);
}

void shiftUp(int index) {
    while (index > 1) {
        int parentIndex = index / 2;
        if (parentIndex >= 1 && heap[index].first < heap[parentIndex].first) {
            swapEl(index, parentIndex);
            index = parentIndex;
        } else {
            break;
        }
    }
}

void heapify(int index) {
    int wantedIndex = index;
    if (index * 2 <= length && heap[index * 2].first < heap[index].first) {
        wantedIndex = index * 2;
    }

    if (index * 2 + 1 <= length && heap[index * 2 + 1].first < heap[wantedIndex].first) {
        wantedIndex = index * 2 + 1;
    }

    if (wantedIndex != index) {
        swapEl(wantedIndex, index);
        heapify(wantedIndex);
    }
}

void deleteElement(int index) {
    swapEl(index, length);
    --length;

    int parentIndex = index / 2;
    if (index > 1 && heap[index] < heap[parentIndex]) {
        shiftUp(index);
    } else {
        heapify(index);
    }
}

int main() {
    ios :: sync_with_stdio(0);
    cin.tie(0);

    int n;
    int total = 0;

    cin >> n;
    for (int query = 1; query <= n; ++query) {
        int type;

        cin >> type;
        if (type == 1) {
            int val;

            cin >> val;

            ++total;
            ++length;

            heap[length].first = val;
            heap[length].second = total;

            v[total] = length;
            shiftUp(length);
        } else if (type == 2) {
            int index;

            cin >> index;
            deleteElement(v[index]);
        } else {
            cout << heap[1].first << '\n';
        }
    }

    return 0;
}