Pagini recente » Cod sursa (job #3357471) | Cod sursa (job #3357473) | Cod sursa (job #90968) | Cod sursa (job #88887) | Cod sursa (job #3357476)
#include <fstream>
#include <vector>
using namespace std;
vector <int> val, h, poz_in_h;
void schimb(int p1, int p2) {
swap(h[p1], h[p2]);
poz_in_h[h[p1]] = p1;
poz_in_h[h[p2]] = p2;
}
int tata(int x) {
return x / 2;
}
void urca(int poz) {
while (poz >= 1 && val[h[poz]] < val[h[tata(poz)]]) {
schimb(poz, tata(poz));
poz = tata(poz);
}
}
void coboara(int p) {
int fs = 2 * p;
int fd = 2 * p + 1;
int pmin = p;
int nh = (int)h.size() - 1;
if (fs <= nh && val[h[fs]] < val[h[pmin]]) {
pmin = fs;
}
if (fd <= nh && val[h[fd]] < val[h[pmin]]) {
pmin = fd;
}
if (pmin != p) {
schimb(pmin, p);
coboara(pmin);
}
}
void adauga(int poz) {
h.push_back(poz);
poz_in_h.push_back((int)h.size() - 1);
urca((int)h.size() - 1);
}
void sterge(int poz) {
if (poz == (int)h.size() - 1) {
h.pop_back();
} else {
schimb(poz, (int)h.size() - 1);
h.pop_back();
urca(poz);
coboara(poz);
}
}
int main() {
ifstream in("heapuri.in");
ofstream out("heapuri.out");
int nr_op;
in >> nr_op;
val.reserve(nr_op + 1);
h.reserve(nr_op + 1);
poz_in_h.reserve(nr_op + 1);
val.push_back(0);
h.push_back(0);
poz_in_h.push_back(0);
for (int i = 0; i < nr_op; i++) {
int tip;
in >> tip;
if (tip == 1) {
int aux;
in >> aux;
val.push_back(aux);
adauga((int)val.size() - 1);
} else if (tip == 2) {
int poz;
in >> poz;
sterge(poz_in_h[poz]);
} else {
out << val[h[1]] << "\n";
}
}
in.close();
out.close();
return 0;
}