Pagini recente » Cod sursa (job #847) | Cod sursa (job #2287342) | Cod sursa (job #1664445) | Cod sursa (job #1577738) | Cod sursa (job #2924366)
#include <fstream>
#include <cassert>
const int nMax = 200001;
struct nod {
int val;
int idx;
bool operator<(const nod &nodNou) const {
return val < nodNou.val;
}
bool operator>(const nod &nodNou) const {
return val > nodNou.val;
}
} v[nMax];
int idx[nMax];
int c;
using namespace std;
int lastPoz = 0;
void urcare(int pozi) {
while (pozi > 1) {
if (v[pozi / 2] > v[pozi]) {
idx[v[pozi].idx] = pozi / 2;
idx[v[pozi / 2].idx] = pozi;
swap(v[pozi], v[pozi / 2]);
pozi /= 2;
} else {
break;
}
}
}
void coborare(int pozi) {
while (pozi * 2 <= lastPoz) {
int pozCopilMin;
if (pozi * 2 + 1 > lastPoz) {
pozCopilMin = pozi * 2;
} else {
if (v[pozi * 2] < v[pozi * 2 + 1]) {
pozCopilMin = pozi * 2;
} else {
pozCopilMin = pozi * 2 + 1;
}
}
if (v[pozi] > v[pozCopilMin]) {
idx[v[pozi].idx] = pozCopilMin;
idx[v[pozCopilMin].idx] = pozi;
swap(v[pozi], v[pozCopilMin]);
pozi = pozCopilMin;
} else {
break;
}
}
}
void inserare(int nr) {
lastPoz += 1;
v[lastPoz].val = nr;
v[lastPoz].idx = lastPoz;
idx[lastPoz] = lastPoz;
urcare(lastPoz);
}
void stergere(int idxi) {
int pozi = idx[idxi];
v[pozi] = v[lastPoz];
lastPoz--;
if (v[pozi].val < v[pozi / 2].val /*&& pozi > 1*/ )
urcare(pozi);
else
coborare(pozi);
}
int main() {
int n, op;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
fin >> n;
for (int i = 0; i < n; i++) {
fin >> op;
switch (op) {
case 1: {
int nr;
fin >> nr;
inserare(nr);
break;
}
case 2: {
int idxi;
fin >> idxi;
stergere(idxi);
break;
}
case 3: {
fout << v[1].val << '\n';
break;
}
default:
assert(false);
}
}
fin.close();
fout.close();
return 0;
}