Pagini recente » Cod sursa (job #2030862) | Cod sursa (job #657417) | Cod sursa (job #2483754) | Cod sursa (job #2202747) | Cod sursa (job #1248790)
#include <iostream>
#include <fstream>
#include <vector>
#define log(...) cout<<__VA_ARGS__<<'\n';
#define NMax 200005
using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
class Heap {
public:
/// Public methods and properties
Heap () {
numberOfNodes = numberOfIndex = 0;
}
int fatherOf (int k) {return k/2;};
int leftSonOf (int k) {return 2*k;};
int rightSonOf (int k) {return 2*k+1;};
void insertOnHeap (int x) {
//log ("Inserting on heap");
numberOfNodes++, numberOfIndex++;
V[numberOfIndex] = x;
H[numberOfNodes] = numberOfIndex;
P[numberOfIndex] = numberOfNodes;
goUp (numberOfNodes);
}
void eraseFromHeap (int index) {
//log ("Erase from heap");
int position = P[index];
H[position] = H[numberOfNodes];
P[index] = -1;
numberOfNodes--;
if (position > 1 && V[H[position]] < V[H[fatherOf(position)]])
goUp(position);
else
goDown(position);
}
int minimumFromHeap () {
//log ("Returning the minimum");
return V[H[1]];
}
private:
/// Private methods and properties
int numberOfNodes, numberOfIndex;
int V[NMax];
int H[NMax];
int P[NMax];
void goUp (int k) {
while (k > 1 && V[H[k]] < V[H[fatherOf(k)]]) {
int aux = H[k];
H[k] = H[fatherOf(k)];
H[fatherOf(k)] = aux;
P[H[k]] = k;
P[H[fatherOf(k)]] = fatherOf(k);
k = fatherOf(k);
}
}
void goDown (int k) {
int son = 1;
while (son) {
son = 0;
if (leftSonOf(k) <= numberOfNodes && H[k] > H[leftSonOf(k)]) {
son = leftSonOf(k);
if (rightSonOf(k) <= numberOfNodes && H[son] < H[rightSonOf(k)])
son = rightSonOf(k);
int aux = H[k];
H[k] = H[son];
H[son] = aux;
P[H[k]] = k;
P[H[son]] = son;
k = son;
} else if (rightSonOf(k) <= numberOfNodes && H[k] > H[rightSonOf(k)]) {
son = rightSonOf(k);
int aux = H[k];
H[k] = H[son];
H[son] = aux;
P[H[k]] = k;
P[H[son]] = son;
k = son;
}
}
}
};
int n;
Heap *customHeap;
int main() {
f>>n;
customHeap = new Heap();
for (int i=1;i<=n;i++) {
int type;
f>>type;
if (type == 1) {
int x;
f>>x;
customHeap->insertOnHeap(x);
} else if (type == 2) {
int x;
f>>x;
customHeap->eraseFromHeap(x);
} else if (type == 3) {
g<<customHeap->minimumFromHeap()<<'\n';
}
}
delete customHeap;
f.close(); g.close();
return 0;
}