Pagini recente » Cod sursa (job #2885046) | Cod sursa (job #2090883) | Cod sursa (job #2563331) | Cod sursa (job #2057236) | Cod sursa (job #1069739)
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
const int MAXN = 200005;
int H[MAXN], order[MAXN];//kind of a struct with the value and the value's serial no.(chronologically)
int heapSize;
//we need to know the serial no. of each value because of operation type 2
//now, for an easy query of the position of the x-th element introduced into the heap
//we use an auxiliary array
int position[MAXN];//position[i] = which node is the i-th element introduced into the heap
int positionSize;//no. of type 1 operations = number of elements introduced into the heap
int N, op, x;
inline int father(int node) {
return node / 2;
}
inline int left_son(int node) {
return 2 * node;
}
inline int right_son(int node) {
return 2 * node + 1;
}
void percolate(int K) {
while (K != 1 && H[K] < H[father(K)]) {
swap(H[K], H[father(K)]);//the values
swap(order[K], order[father(K)]);//the chronological order in which the values were introduced
swap(position[order[K]], position[order[father(K)]]);
K = father(K);
}
}
void sift(int K) {
int son;
do {
//
if (heapSize >= left_son(K)) {
if (H[right_son(K)] < H[left_son(K)])
son = right_son(K);
else
son = left_son(K);
}else if (heapSize == right_son(K))
son = right_son(K);
else
son = 0;//no sons
//this chunk of code chooses the smallest son of node K, if there are any
if (son && H[son] < H[K]) {
swap(H[K], H[son]);
swap(order[K], order[son]);
swap(position[order[K]], position[order[son]]);
K = son;
}else son = 0;
}while (son);
}
void cut(int K) {
H[K] = H[heapSize];
order[K] = order[heapSize];
position[order[K]] = position[order[heapSize]];
heapSize--;
percolate(K);
sift(K);
}
//void write() {
// for (int i = 1; i <= heapSize; ++i)
// cout << H[i] << ' ';
// cout << '\n';
//}
int main() {
fin >> N;
for (int i = 0; i < N; ++i) {
fin >> op;
if (op == 1) {// insert x into the heap
fin >> x;
H[++heapSize] = x;
order[heapSize] = ++positionSize;
position[positionSize] = heapSize;
percolate(heapSize);
}
else
if (op == 2) {// erase the x-th element that has been introduced into the heap
fin >> x;
cut(position[x]);
}
else
if (op == 3)// print the smallet value in the heap
fout << H[1] << '\n';
//write();
}
fin.close();
fout.close();
return 0;
}