Pagini recente » Cod sursa (job #451321) | Cod sursa (job #2926218) | Cod sursa (job #181157) | Cod sursa (job #1058096) | Cod sursa (job #3306600)
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
string filename = "heapuri";
ifstream fin(filename + ".in");
ofstream fout(filename + ".out");
struct Nod
{
int val;
int idx;
};
const int NMAX = 2e5;
Nod heap[NMAX + 5];
int xPos[NMAX + 5];
void swapNodes(int nod1, int nod2)
{
swap(heap[nod1], heap[nod2]);
swap(xPos[heap[nod1].idx], xPos[heap[nod2].idx]);
}
void compareTop(int nodPos)
{
while ((nodPos > 1) and (heap[nodPos].val < heap[nodPos / 2].val))
{
swapNodes(nodPos, nodPos / 2);
nodPos = nodPos / 2;
}
}
void compareBottom(int nodPos, int &hsize)
{
int son = -1;
if (nodPos * 2 <= hsize)
{
son = nodPos * 2;
if ((nodPos * 2 + 1 <= hsize) and (heap[nodPos * 2 + 1].val < heap[nodPos * 2].val))
{
son = nodPos * 2 + 1;
}
}
if (son == -1)
return;
if (heap[son].val < heap[nodPos].val)
{
swapNodes(son, nodPos);
compareBottom(son, hsize);
}
}
void insertElement(int xval, int xIPos, int &hsize)
{
hsize++;
heap[hsize].val = xval;
heap[hsize].idx = xIPos;
xPos[heap[hsize].idx] = hsize;
compareTop(hsize);
}
void deleteX(int idx, int &hsize)
{
int cPos = xPos[idx];
swapNodes(cPos, hsize);
hsize--;
compareTop(cPos);
compareBottom(cPos, hsize);
}
int main()
{
int n;
fin>>n;
int hsize = 0, inserted = 0;
for(int i=1;i<=n;i++)
{
int type, x;
fin >> type;
if (type == 1)
{
fin >> x;
inserted ++;
insertElement(x, inserted, hsize);
}
if (type == 2)
{
fin >> x;
deleteX(x, hsize);
}
if(type == 3)
{
fout<<heap[1].val<<'\n';
}
}
return 0;
}