Pagini recente » Cod sursa (job #2672968) | Cod sursa (job #1297566) | Autentificare | Cod sursa (job #1995979) | Cod sursa (job #1265880)
// Craciun Catalin
// Heapuri
#include <iostream>
#include <fstream>
#include <unistd.h>
#define NMax 200005
#define inf 1<<30
#define log(...) cout<<__VA_ARGS__<<'\n';
using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
class CustomHeap {
public:
// Properties
int size; // Heap's size
// Methods
void insertValue(int x) {
// log("Inserting value " << x);
size++;
indexNumber++;
H[size] = indexNumber;
V[indexNumber] = x;
poz[indexNumber] = size;
goUp(size);
}
void eraseIndex(int index) {
// log("Erasing index " << index);
int positionToErase = poz[index];
H[positionToErase] = H[size];
size--;
if (positionToErase > 1 && V[H[positionToErase]] < V[H[positionToErase/2]])
goUp(positionToErase);
else
goDown(positionToErase);
}
int queryMinimum() {
// log("Querying minimum");
return V[H[1]];
}
CustomHeap() {
size = 0;
indexNumber = 0;
}
private:
int indexNumber;
int H[NMax];
int V[NMax];
int poz[NMax];
int minim (int a, int b) {
if (a < b) return a; return b;
}
void goUp(int position) {
int aux;
while (position > 1 && V[H[position]] < V[H[position/2]]) {
aux = H[position];
H[position] = H[position/2];
H[position/2] = aux;
poz[H[position]] = position;
poz[H[position/2]] = position/2;
position = position/2;
}
}
void goDown(int position) {
int x = position, aux;
while (x <= size) {
int value = inf, pValue = -1;
if (x * 2 <= size) { value = V[H[x * 2]]; pValue = x*2; }
if (x * 2 + 1 <= size) { value = minim(value, V[H[x * 2 + 1]]); if (value == V[H[x*2+1]]) pValue = 2*x+1; }
if (pValue == -1) break;
if (value >= V[H[x]]) break;
aux = H[x];
H[x] = H[pValue];
H[pValue] = aux;
poz[H[x]] = x;
poz[H[pValue]] = pValue;
x = pValue;
}
}
};
CustomHeap *customHeap;
int main() {
customHeap = new CustomHeap();
int n;
f>>n;
for (int i=1;i<=n;i++) {
int type;
int read;
f>>type;
if (type < 3)
f>>read;
switch (type) {
case 1:
customHeap -> insertValue(read);
break;
case 2:
customHeap -> eraseIndex(read);
break;
case 3:
g<<customHeap -> queryMinimum()<<'\n';
break;
default:
break;
}
}
delete customHeap;
f.close(); g.close();
return 0;
}