Pagini recente » Cod sursa (job #1329759) | Cod sursa (job #2796494) | Cod sursa (job #1737629) | Cod sursa (job #2467992) | Cod sursa (job #790184)
Cod sursa(job #790184)
#include <vector>
#include <fstream>
#include <iostream>
#define INS 1
#define DEL 2
#define MIN 3
#define LEFT(x) ((x) << 1)
#define RIGT(x) (((x) << 1) + 1)
#define PARENT(x) ((x) >> 1)
using namespace std;
vector<int> heap;
vector<int> value;
vector<int> heap_pos;
void swap(int &x, int &y) {
int aux = x;
x = y;
y = aux;
}
void insert(int x)
{
heap_pos.push_back(heap.size());
heap.push_back(value.size());
value.push_back(x);
int node = heap.size() - 1;
while (node != 1) {
if (value[heap[node]] < value[heap[node / 2]]) {
swap(heap[node], heap[node / 2]);
heap_pos[heap[node]] = node;
heap_pos[heap[node / 2]] = node / 2;
node = node / 2;
} else {
break;
}
}
}
void remove(int x)
{
swap(heap[heap_pos[x]], heap[heap.size() - 1]);
heap.pop_back();
int node = heap_pos[x];
heap_pos[heap[node]] = node;
while (node * 2 < (int)heap.size()) {
int next = -1;
if ((int)heap.size() - 1 == node * 2) {
next = node * 2;
} else {
if (value[heap[node * 2]] < value[heap[node * 2 + 1]]) {
next = node * 2;
} else {
next = node * 2 + 1;
}
}
if (value[heap[node]] > value[heap[next]]) {
heap_pos[heap[node]] = next;
heap_pos[heap[next]] = node;
swap(heap[node], heap[next]);
} else {
break;
}
node = next;
}
}
int main(void) {
heap.push_back(0);
value.push_back(0);
heap_pos.push_back(0);
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
int n;
fin >> n;
while (n--) {
int op, x;
fin >> op;
if (op == INS) {
fin >> x;
insert(x);
} else if (op == DEL) {
fin >> x;
remove(x);
} else if (op == MIN) {
fout << value[heap[1]] << '\n';
}
}
return 0;
}