Pagini recente » Cod sursa (job #2292939) | Cod sursa (job #229583) | Cod sursa (job #692675) | Cod sursa (job #1820988) | Cod sursa (job #2734515)
#include <bits/stdc++.h>
using namespace std;
struct Node {
int value;
int index;
};
Node heap[200005];
int xPos[200010];
int father(int nodePos) {
return nodePos / 2;
}
int leftSon (int nodePos) {
return 2 * nodePos;
}
int rightSon (int node) {
return 2 * node + 1;
}
void swapNodes (int node1, int node2) {
swap(heap[node1], heap[node2]);
swap(xPos[heap[node1].index], xPos[heap[node2].index]);
}
void topComparison (int nodePos) {
while ((nodePos > 1) && (heap[nodePos].value < heap[father(nodePos)].value)) {
swapNodes(nodePos, father(nodePos));
nodePos = father(nodePos);
}
}
void bottomComparison (int nodePos, int &heapsize) {
int son = -1;
if (leftSon(nodePos) <= heapsize) {
son = leftSon(nodePos);
if ((rightSon(nodePos) <= heapsize) && (heap[rightSon(nodePos)].value < heap[leftSon(nodePos)].value)) {
son = rightSon(nodePos);
}
}
if (son == -1) return;
if (heap[son].value < heap[nodePos].value) {
swapNodes(son, nodePos);
bottomComparison(son, heapsize);
}
}
void insertElement(int xValue, int xInitialPos, int &heapsize) {
heapsize = heapsize + 1;
heap[heapsize].value = xValue;
heap[heapsize].index = xInitialPos;
xPos[heap[heapsize].index] = heapsize;
topComparison(heapsize);
}
void deleteX(int index, int &heapsize) {
int currentPosition = xPos[index];
swapNodes(currentPosition, heapsize);
heapsize = heapsize - 1;
topComparison(currentPosition);
bottomComparison(currentPosition, heapsize);
}
int main()
{
ifstream fin ("heapuri.in");
ofstream fout ("heapuri.out");
int N, heapsize = 0, inserted = 0;
fin >> N;
for (int i = 1; i <= N; ++i) {
int operationType, x;
fin >> operationType;
if (operationType == 1) {
fin >> x;
inserted += 1;
insertElement(x, inserted, heapsize);
} else if (operationType == 2) {
fin >> x;
deleteX(x, heapsize);
} else {
fout << heap[1].value << "\n";
}
}
return 0;
}