Pagini recente » Cod sursa (job #878187) | Cod sursa (job #1701795) | Cod sursa (job #550892) | Cod sursa (job #1516771) | Cod sursa (job #1083328)
#include <vector>
#include <iostream>
#include <fstream>
using namespace std;
struct nod
{
int val, poz;
};
int getFather(int n)
{
if (n == 0)
return 0;
return (n+1) / 2 - 1;
}
int getLeftSon(int n)
{
return (n+1) * 2 - 1;
}
int getRightSon(int n)
{
return (n+1) * 2;
}
int getMin(vector<nod> &heap)
{
return heap[0].val;
}
void swap(nod &a, nod &b)
{
nod temp;
temp = a;
a = b;
b = temp;
}
void sift(vector<nod> &heap, int k)
{
while (heap.size() > getRightSon(k) && (heap[k].val > heap[getRightSon(k)].val || heap[k].val > heap[getLeftSon(k)].val))
{
int min = (heap[getRightSon(k)].val < heap[getLeftSon(k)].val) ? getRightSon(k) : getLeftSon(k);
if (heap[k].val > heap[min].val)
{
swap(heap[k], heap[min]);
k = min;
}
}
if (heap.size() == getRightSon(k))
{
if (heap[k].val > heap[getLeftSon(k)].val)
{
swap(heap[k], heap[getLeftSon(k)]);
k = getLeftSon(k);
}
}
}
void percolate(vector<nod> &heap, int k)
{
while (k > 0 && heap[k].val < heap[getFather(k)].val)
{
swap(heap[k], heap[getFather(k)]);
k = getFather(k);
}
}
void buildHeap(vector<nod> &heap)
{
for (int i = heap.size() / 2; i >= 0; i--)
{
sift(heap, i);
}
}
void cut(vector<nod> &heap, int k)
{
swap(heap[k], heap[heap.size() - 1]);
heap.pop_back();
if (heap[k].val < heap[getFather(k)].val)
percolate(heap, k);
else
sift(heap, k);
}
void insert(vector<nod> &heap, nod val)
{
heap.push_back(val);
percolate(heap, heap.size() - 1);
}
int getPos(vector<nod> &heap, int val)
{
for (int i = 0; i < heap.size(); i++)
{
if (heap[i].poz == val)
return i;
}
}
int main()
{
vector<nod> Heap;
ifstream IN("heapuri.in");
ofstream OUT("heapuri.out");
int n; IN >> n;
int index = 1;
while (n--)
{
int ar1; IN >> ar1;
if (ar1 == 3)
OUT << getMin(Heap) << "\n";
else
{
int ar2; IN >> ar2;
if (ar1 == 1)
{
nod toadd;
toadd.poz = index++;
toadd.val = ar2;
insert(Heap, toadd);
}
else
{
cut(Heap, getPos(Heap, ar2));
}
}
}
}