Pagini recente » Cod sursa (job #305554) | Cod sursa (job #3246282) | Cod sursa (job #882350) | Cod sursa (job #1491118) | Cod sursa (job #1591678)
#include <fstream>
#include <string.h>
#include <algorithm>
#define NMax 200010
using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
int queries, H[NMax], heapPos[NMax], last, num, vals[NMax];
int father(int node)
{
return node / 2;
}
int leftSon(int node)
{
return 2 * node;
}
int rightSon(int node)
{
return 2 * node + 1;
}
void upHeap(int node)
{
while (node > 1 && vals[H[node]] < vals[H[father(node)]]) {
swap(heapPos[H[node]], heapPos[H[father(node)]]);
swap(H[node], H[father(node)]);
node = father(node);
}
}
void downHeap(int node)
{
while (node <= last / 2) {
int pos = leftSon(node);
if (rightSon(node) <= last && vals[H[rightSon(node)]] < vals[H[leftSon(node)]])
pos = rightSon(node);
if (pos != -1) {
swap(heapPos[H[node]], heapPos[H[pos]]);
swap(H[node], H[pos]);
node = pos;
}
else
break;
}
}
void insertHeap(int val)
{
vals[++num] = val;
H[++last] = num;
heapPos[num] = last;
upHeap(last);
}
void deleteHeap(int nth)
{
int pos = heapPos[nth];
heapPos[H[last]] = pos;
H[pos] = H[last];
last--;
if (pos > 1 && vals[H[pos]] > vals[H[father(pos)]])
upHeap(pos);
else
downHeap(pos);
}
int dispTop()
{
return vals[H[1]];
}
int main()
{
f >> queries;
int cmd, x;
for (int i = 1; i <= queries; i++) {
f >> cmd;
if (cmd == 1) {
f >> x;
insertHeap(x);
}
else if (cmd == 2) {
f >> x;
deleteHeap(x);
}
else
g << dispTop() << "\n";
}
return 0;
}