Cod sursa(job #3124322)

Utilizator mex7Alexandru Valentin mex7 Data 27 aprilie 2023 20:37:02
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.06 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 shiftUp(int index) {
    while (index > 1) {
        int parentIndex = index / 2;
        if (heap[index].first < heap[parentIndex].first) {
            v[heap[index].second] = parentIndex;
            v[heap[parentIndex].second] = index;
            swap(heap[index], heap[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) {
        v[heap[wantedIndex].second] = index;
        v[heap[index].second] = wantedIndex;
        swap(heap[index], heap[wantedIndex]);
        heapify(wantedIndex);
    }
}

void deleteElement(int index) {
    swap(heap[index], heap[length]);
    --length;

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

void print() {
    for (int i = 1; i <= length; ++i) {
        cout << heap[i].first << ' ';
    }
    cout << '\n';
}

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;

            ++length;
            heap[length].first = val;
            v[++total] = length;
            heap[length].second = total;
            shiftUp(length);
        } else if (type == 2) {
            int index;

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

    return 0;
}