Pagini recente » Cod sursa (job #2791532) | Cod sursa (job #751117) | Cod sursa (job #350821) | Cod sursa (job #2490248) | Cod sursa (job #2775907)
#include <bits/stdc++.h>
#define ll long long
#define lsb(x) x & -x
using namespace std;
class Heap {
private:
vector<int> heap;
vector<int> heapToPos; //pos in heap -> pos in reality
vector<int> posToHeap; //pos in reality -> pos in heap
vector<int> elements;
public:
void swapNodes(int a, int b) {
swap(heap[a], heap[b]);
swap(heapToPos[a], heapToPos[b]);
swap(posToHeap[heapToPos[a]], posToHeap[heapToPos[b]]);
}
void goUP(int node) {
if(node == 0)
return;
if(heap[node] < heap[node / 2]) {
swapNodes(node, node / 2);
goUP(node / 2);
}
}
void add(int x) {
heap.push_back(x);
heapToPos.push_back(elements.size());
posToHeap.push_back(heap.size() - 1);
elements.push_back(x);
goUP(heap.size() - 1);
}
void goDOWN(int node) {
int dest = -1;
if(node * 2 < heap.size() && heap[node] > heap[node * 2])
dest = node * 2;
if(node * 2 + 1 < heap.size() && heap[node] > heap[node * 2 + 1])
dest = node * 2 + 1;
if(dest != -1) {
swapNodes(node, dest);
goDOWN(dest);
}
}
void remove(int pos) {
int tmp = posToHeap[pos]; ///aici!!!
swapNodes(heap.size() - 1, posToHeap[pos]);
heap.pop_back();
heapToPos.pop_back();
if(tmp < heap.size()) {
goUP(tmp);
goDOWN(tmp);
}
posToHeap[pos] = -1;
}
int getMin() {
return heap[0];
}
void print() {
for(auto it : heap)
cout << it << " ";
cout << endl;
for(auto it : heapToPos)
cout << it << " ";
cout << endl;
for(auto it : posToHeap)
cout << it << " ";
cout << endl;
cout << endl;
}
};
int main() {
ifstream cin("heapuri.in");
ofstream cout("heapuri.out");
int ntests;
cin >> ntests;
Heap myHeap;
while(ntests --) {
int type;
cin >> type;
if(type == 1) {
int x;
cin >> x;
myHeap.add(x);
} else if(type == 2) {
int x;
cin >> x;
x --;
myHeap.remove(x);
} else {
cout << myHeap.getMin() << "\n";
}
//myHeap.print();
}
return 0;
}