Cod sursa(job #3264732)

Utilizator Barbu_MateiBarbu Matei Barbu_Matei Data 23 decembrie 2024 17:09:57
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <bits/stdc++.h>
using namespace std;

int n, k;
int h[400002], insertKey[400002];
int insertPos[200001], insertVal;

void percolate(int pos) {
    while (pos / 2 > 0 && h[pos / 2] > h[pos]) {
        swap(h[pos / 2], h[pos]);
        swap(insertPos[insertKey[pos / 2]], insertPos[insertKey[pos]]);
        swap(insertKey[pos / 2], insertKey[pos]);
        pos = pos / 2;
    }
}

void sift(int pos) {
    while (1) {
        int child = 2 * pos;
        if (child > k) {
            break;
        }
        if (child + 1 <= k && h[child + 1] < h[child]) {
            ++child;
        }
        if (h[pos] > h[child]) {
            swap(h[pos], h[child]);
            swap(insertPos[insertKey[child]], insertPos[insertKey[pos]]);
            swap(insertKey[child], insertKey[pos]);
            pos = child;
        } else {
            break;
        }
    }
}

void inserth(int node) {
    ++insertVal;
    h[++k] = node;
    insertKey[k] = insertVal;
    insertPos[insertVal] = k;
    percolate(k);
}

void deleteh(int pos) {
    pos = insertPos[pos];
    swap(h[pos], h[k]);
    insertPos[insertKey[k]] = pos;
    insertKey[pos] = insertKey[k];
    --k;
    sift(pos);
}

int main() {
    ifstream cin("heapuri.in");
    ofstream cout("heapuri.out");
    cin >> n;
    while (n--) {
        int op, x;
        cin >> op;
        if (op == 1) {
            cin >> x;
            inserth(x);
        } else if (op == 2) {
            cin >> x;
            deleteh(x);
        } else if (op == 3) {
            cout << h[1] << "\n";
        }
    }
}