Pagini recente » Cod sursa (job #632141) | Cod sursa (job #666092) | Cod sursa (job #1508897) | Cod sursa (job #574405) | Cod sursa (job #2740682)
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
int heap[200100], nr[200100], pos[200100];
int nrActiuni, actiune, nrElem = 0, nrk = 0;
int father(int nod) {
return nod / 2;
}
int left_son(int nod) {
return 2 * nod;
}
int right_son(int nod) {
return 2 * nod + 1;
}
void percolate(int nod) {
int key = heap[nod];
while ((nod > 1) and (key < heap[father(nod)])) {
heap[nod] = heap[father(nod)];
pos[heap[father(nod)]] = nod;
nod = father(nod);
}
heap[nod] = key;
pos[key] = nod;
}
void shift(int nod) {
int son;
do {
son = 0;
if (left_son(nod) <= nrElem) {
son = left_son(nod);
if (right_son(nod) <= nrElem and heap[right_son(nod)] < heap[left_son(nod)]) {
son = right_son(nod);
}
}
if (heap[son] >= heap[nod]) {
son = 0;
}
if (son) {
swap(heap[nod], heap[son]);
swap(pos[heap[son]], pos[heap[nod]]);
nod = son;
}
} while (son);
}
//void deleteElem(int nod) {
// heap[nod] = heap[nrElem];
// nrElem--;
//
// if (nod > 1 and heap[nod] < heap[father(nod)]) percolate(nod);
// else shift(nod);
//}
void push(int nod) {
heap[++nrElem] = nod;
pos[heap[nrElem]] = nrElem;
percolate(nrElem);
}
void pop(int nod) {
int index = pos[nod];
swap(heap[index], heap[nrElem]);
swap(pos[heap[index]], pos[heap[nrElem]]);
nrElem--;
percolate(index);
shift(index);
}
int main() {
fin >> nrActiuni;
for (int i = 0; i < nrActiuni; i++) {
fin >> actiune;
if (actiune == 1) {
int elem;
fin >> elem;
nr[++nrk] = elem;
push(nrk);
} else if (actiune == 2) {
int poz;
fin >> poz;
pop(poz);
} else if (actiune == 3) fout << heap[1] << endl;
}
return 0;
}