Pagini recente » Istoria paginii runda/ccex-2013-clasa-a-9-a/clasament | Istoria paginii runda/prega_oji2015_x_2/clasament | Istoria paginii runda/ojiprep2/clasament | Monitorul de evaluare | Cod sursa (job #879427)
Cod sursa(job #879427)
#include <fstream>
using namespace std;
ifstream in("heapuri.in");
ofstream out("heapuri.out");
int crono[200001];
struct MinHeap {
MinHeap(int n = 1) { H = new int[n+1]; N = 0; }
~MinHeap() { delete[] H; }
int min() { return H[1]; }
void push(int);
void cut(int);
int find(int&, int);
private:
int * H; int N;
int father(int nod) { return nod / 2; }
int leftSon(int nod) { return 2 * nod; }
int rightSon(int nod) { return 2 * nod + 1; }
void sift(int);
void percolate(int);
void swap(int &a, int &b) { int t = a; a = b; b = t; }
};
void MinHeap::sift(int nod)
{
do
{
if (rightSon(nod) <= N && H[rightSon(nod)] < H[nod])
{
swap(H[nod], H[leftSon(nod)]);
swap( H[leftSon(nod)], H[rightSon(nod)] );
nod = rightSon(nod);
}
else if (leftSon(nod) <= N)
{
swap(H[nod], H[leftSon(nod)]);
nod = leftSon(nod);
}
else break;
} while (nod <= N);
}
void MinHeap::percolate(int nod)
{
int key = H[nod];
while ( (nod > 1) && (key < H[father(nod)]) )
{
H[nod] = H[father(nod)];
if (rightSon(father(nod)) <= N)
{
if ( leftSon(father(nod)) > rightSon(father(nod)) )
swap( H[leftSon(father(nod))], H[rightSon(father(nod))] );
}
nod = father(nod);
}
H[nod] = key;
}
int MinHeap::find(int &val, int i = 1)
{
if (val == H[i]) return i;
else if (rightSon(i) <= N && val >= H[rightSon(i)]) return find(val, rightSon(i));
else if (leftSon(i) <= N && val >= H[leftSon(i)]) return find(val, leftSon(i));
else return -1;
}
void MinHeap::push(int val)
{
H[++N] = val;
percolate(N);
}
void MinHeap::cut(int val)
{
int i = find(val);
H[i] = 1e9 + 1; // Inf
sift(i);
N--;
}
int main()
{
int n, c = 0, x, y; in >> n;
MinHeap hp(n);
for (int i = 0; i < n; i++)
{
in >> x;
switch(x)
{
case 1: { in >> y; hp.push(y); crono[++c] = y; } break;
case 2: { in >> y; hp.cut(crono[y]); } break;
case 3: out << hp.min() << '\n'; break;
}
}
return 0;
}