Pagini recente » Cod sursa (job #3276789) | Cod sursa (job #2045032) | Cod sursa (job #556880) | Cod sursa (job #1784009) | Cod sursa (job #2484747)
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
int father(int i) {
return i / 2;
}
int left_son(int i) {
return 2 * i;
}
int right_son(int i) {
return 2 * i + 1;
}
void percolate(vector<pair <int, int>> &heap, int k, vector<int> &pos) {
pair<int, int> val = heap[k];
while (k > 1 && heap[father(k)].first > val.first) {
heap[k] = heap[father(k)];
pos[heap[father(k)].second] = k;
k = father(k);
}
heap[k] = val;
pos[val.second] = k;
return;
}
void sift(vector<pair <int, int>> &heap, int k, int n, vector<int> &pos) {
int son;
do {
son = -1;
if (left_son(k) <= n) {
son = left_son(k);
if (right_son(k) <= n && heap[right_son(k)].first < heap[left_son(k)].first)
son = right_son(k);
if (heap[k].first > heap[son].first) {
swap(pos[heap[k].second], pos[heap[son].second]);
swap(heap[k], heap[son]);
k = son;
} else {
son = -1;
}
}
} while (son > 0);
return;
}
void delete_element(vector<pair <int, int>> &heap, int init_k, vector<int> &pos) {
int cur_k = pos[init_k];
swap(pos[heap[cur_k].second], pos[heap[heap.size() - 1].second]);
swap(heap[cur_k], heap[heap.size() - 1]);
pos[heap[heap.size() - 1].second] = 0;
heap.pop_back();
if (heap.size() > 1) {
percolate(heap, cur_k, pos);
sift(heap, cur_k, heap.size() - 1, pos);
}
return;
}
int main() {
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
int n; fin >> n;
vector<pair <int, int>> a(n);
for (int i = 0; i < n; i++) {
fin >> a[i].first;
if (a[i].first == 1 || a[i].first == 2) {
fin >> a[i].second;
}
}
vector<int> pos(1, 0);
vector<pair <int, int>> heap;
heap.push_back({0, 0});
for (int i = 0; i < n; i++) {
if (a[i].first == 1) {
heap.push_back({a[i].second, pos.size()});
pos.push_back(heap.size());
percolate(heap, heap.size() - 1, pos);
} else if (a[i].first == 2) {
delete_element(heap, a[i].second, pos);
} else {
fout << heap[1].first << "\n";
}
}
return 0;
}