Pagini recente » Cod sursa (job #1092783) | Cod sursa (job #2103553) | Cod sursa (job #1548843) | Autentificare | Cod sursa (job #310084)
Cod sursa(job #310084)
#include <fstream>
using namespace std;
#define NUME "heapuri"
ifstream fi(NUME".in");
ofstream fo(NUME".out");
#define MAX 200010
#define cmp(a, b) (a > b)
class Heap {
private:
int H[MAX], A[MAX], size;
// cmp: Dist[A] > Dist[B] (fiu, tata)
public:
int Poz[MAX];
int counter;
Heap(int n) {
//H = new int[n+1];
//A = new int[n+1];
size = 0;
counter = 0;
}
int top() {
return A[H[1]];
}
bool empty() {
return size == 0;
}
int heapup(int x) {
int key = A[H[x]];
while (x > 1 && !cmp(key, A[H[x >> 1]])) {
//H[x] = H[x >> 1];
swap(H[x], H[x >> 1]);
Poz[H[x]] = x;
Poz[H[x >> 1]] = x >> 1;
x = x >> 1;
}
//H[x] = key;
return x;
}
int heapdown(int x) {
int fiu;
while( x*2 <= size && !cmp(A[H[x*2]], A[H[x]]) ||
x*2+1 <= size && !cmp(A[H[x*2+1]], A[H[x]]) ) {
fiu = cmp(A[H[x*2]], A[H[x*2+1]]) ? x*2+1 : x*2;
swap(H[x], H[fiu]);
Poz[H[x]] = x;
Poz[H[fiu]] = fiu;
x = fiu;
}
return x;
}
void push(int who) {
// i actually insert `counter` into the heap
A[++counter] = who;
H[++size] = counter;
Poz[counter] = size;
heapup(size);
//Poz[counter] = heapup(size);
}
void pop() {
H[1] = H[size--];
heapdown(1);
}
void remove(int position) {
int x = Poz[position];
H[x] = H[size--];
Poz[H[x]] = x;
//if (x > 1 && !cmp(A[x], A[x/2])) {
// heapup(x);
//} else {
if (heapup(x) == x) {
heapdown(x);
}
}
} H(MAX);
int main()
{
int N, op, x;
fi >> N;
while (N--) {
fi >> op;
if (op != 3) {
fi >> x;
if (op == 1)
H.push(x);
else
H.remove(x);
} else {
fo << H.top() << "\n";
}
}
return 0;
}