Pagini recente » Cod sursa (job #3310403) | Borderou de evaluare (job #1975062) | Cod sursa (job #3357087) | Cod sursa (job #228375) | Cod sursa (job #3340995)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
static const int MAXQ = 200000 + 5;
int h[MAXQ]; // heap: stocheaza id-uri
int posi[MAXQ]; // posi[id] = pozitia id-ului in heap
int val[MAXQ]; // val[id] = valoarea inserata
int sz = 0; // dimensiunea heap-ului
int idCnt = 0; // cate inserari am facut (id curent)
inline bool cmpId(int id1, int id2) {
return val[id1] < val[id2];
}
inline void swapHeap(int a, int b) {
int ida = h[a], idb = h[b];
h[a] = idb; h[b] = ida;
posi[ida] = b;
posi[idb] = a;
}
void siftUp(int i) {
while (i > 1) {
int p = i / 2;
if (cmpId(h[i], h[p])) {
swapHeap(i, p);
i = p;
} else break;
}
}
void siftDown(int i) {
while (true) {
int l = i * 2;
int r = l + 1;
int best = i;
if (l <= sz && cmpId(h[l], h[best])) best = l;
if (r <= sz && cmpId(h[r], h[best])) best = r;
if (best != i) {
swapHeap(i, best);
i = best;
} else break;
}
}
void heapPush(int x) {
++idCnt;
val[idCnt] = x;
h[++sz] = idCnt;
posi[idCnt] = sz;
siftUp(sz);
}
void heapEraseById(int id) {
int i = posi[id]; // pozitia in heap
swapHeap(i, sz);
posi[id] = 0; // optional: marcam sters
--sz;
if (i <= sz) {
// dupa swap, elementul de pe pozitia i poate trebui urcat sau coborat
siftUp(i);
siftDown(i);
}
}
int heapMin() {
return val[h[1]];
}
int main() {
ios::sync_with_stdio(false);
fin.tie(nullptr);
freopen("heapuri.in", "r", stdin);
freopen("heapuri.out", "w", stdout);
int q;
cin >> q;
while (q--) {
int t;
fin >> t;
if (t == 1) {
int x; fin >> x;
heapPush(x);
} else if (t == 2) {
int k; fin >> k;
heapEraseById(k);
} else { // t == 3
fout << heapMin() << "\n";
}
}
return 0;
}