Pagini recente » Cod sursa (job #2318161) | Cod sursa (job #1701379) | Cod sursa (job #894907) | Cod sursa (job #1319813) | Cod sursa (job #944593)
Cod sursa(job #944593)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
using namespace std;
class SkewHeap {
public:
SkewHeap() : root(NULL), pos(1) { }
SkewHeap( int key ) {
root = new Node(key);
pos.resize(2);
pos[1] = root;
}
void meld( SkewHeap & H ) {
root = meld( root, H.root );
}
void insert( int val ) {
Node * t = new Node(val);
root = meld( root, t );
pos.push_back(t);
}
int & top() {
return root->key;
}
void pop() {
Node * new_root = meld( root->left, root->right );
delete root;
root = new_root;
}
private:
struct Node {
Node( int key ) : left(NULL), right(NULL), key(key) {}
Node * left;
Node * right;
Node * parent;
int key;
};
Node * root;
bool cmp( Node * t1, Node * t2 ) {
return t1->key < t2->key;
}
Node * meld( Node * t1, Node * t2 ) {
if (t1 == NULL) return t2;
if (t2 == NULL) return t1;
if (!cmp(t1, t2)) swap(t1, t2);
t1->right = meld( t1->right, t2 );
if (t1->right != NULL) {
t1->right->parent = t1;
}
swap( t1->left, t1->right );
return t1;
}
public:
vector<Node *> pos;
void erase( Node * t ) {
if (t == root) {
pop();
return;
}
Node * tmp = meld( t->left, t->right );
if (t->parent->left == t) t->parent->left = tmp;
else t->parent->right = tmp;
delete t;
}
};
int main() {
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
int n;
fin >> n;
SkewHeap a;
for (int i = 1; i <= n; ++i) {
int op, x;
fin >> op;
switch (op) {
case 1: fin >> x;
a.insert(x);
break;
case 2: fin >> x;
a.erase(a.pos[x]);
break;
case 3: fout << a.top() << '\n';
break;
}
}
return 0;
}