Pagini recente » Cod sursa (job #1450767) | Cod sursa (job #1970461) | Cod sursa (job #818676) | Cod sursa (job #1671626) | Cod sursa (job #2775908)
#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;
int size = 0;
public:
Heap() {
heap.resize(1, 0);
heapToPos.resize(1, 0);
posToHeap.resize(1, 0);
elements.resize(1, 0);
}
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 == 1)
return;
if(heap[node] < heap[node / 2]) {
swapNodes(node, node / 2);
goUP(node / 2);
}
}
void add(int x) {
size ++;
heap.push_back(x);
heapToPos.push_back(elements.size());
posToHeap.push_back(size);
elements.push_back(x);
goUP(size);
}
void goDOWN(int node) {
int dest = -1;
if(node * 2 <= size && heap[node] > heap[node * 2])
dest = node * 2;
if(node * 2 + 1 <= 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(size, posToHeap[pos]);
//print();
heap.pop_back();
heapToPos.pop_back();
size --;
if(tmp <= size) {
goUP(tmp);
goDOWN(tmp);
}
posToHeap[pos] = -1;
}
int getMin() {
return heap[1];
}
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;
myHeap.remove(x);
} else {
cout << myHeap.getMin() << "\n";
}
//myHeap.print();
}
return 0;
}