Pagini recente » Cod sursa (job #3352220) | Cod sursa (job #834776) | Cod sursa (job #1835548) | Cod sursa (job #2791301) | Cod sursa (job #3319057)
#include <fstream>
#include <vector>
using namespace std;
class Heap
{
public:
Heap();
void insert(int x);
void remove(int i);
int min() const;
private:
void Swap(int i, int j);
int n;
int insertCount;
vector<pair<int, int>> heap;
vector<int> pos;
};
int main()
{
int n, q, x;
Heap heap;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
fin >> n;
while (n--)
{
fin >> q;
switch (q)
{
case 1:
{
fin >> x;
heap.insert(x);
break;
}
case 2:
{
fin >> x;
heap.remove(x);
break;
}
case 3:
{
fout << heap.min() << '\n';
break;
}
}
}
fin.close();
fout.close();
}
Heap::Heap() : n{0}, insertCount{0}, heap{}, pos{vector<int>(1)}
{}
void Heap::insert(int x)
{
insertCount++;
n++;
heap.emplace_back(x, insertCount);
pos.push_back(n - 1);
for (int i = n - 1; i > 0 && heap[i].first < heap[(i - 1) / 2].first; i = (i - 1) / 2)
Swap(i, (i - 1) / 2);
}
void Heap::remove(int i)
{
// Swap i with the last element from the heap.
int j = pos[i];
Swap(j, n - 1);
// Delete the last element from the heap
heap.pop_back();
n--;
if (j > n - 1)
return;
while (true)
{
if (const int child = 2 * j + 1; child < n && heap[j].first > heap[child].first)
{
Swap(j, child);
j = child;
continue;
}
if (const int child = 2 * j + 2; child < n && heap[j].first > heap[child].first)
{
Swap(j, child);
j = child;
continue;
}
if (const int parent = (j - 1) / 2; parent >= 0 && heap[parent].first > heap[j].first)
{
Swap(parent, j);
j = parent;
continue;
}
break;
}
}
int Heap::min() const
{
return heap[0].first;
}
void Heap::Swap(int i, int j)
{
swap(heap[i], heap[j]);
pos[heap[i].second] = i;
pos[heap[j].second] = j;
}