Pagini recente » Cod sursa (job #1973041) | Cod sursa (job #1647861) | Cod sursa (job #2629018) | Cod sursa (job #100095) | Cod sursa (job #3126663)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
// functie pentru adaugarea unui element in heap
void insert(vector<int> &heap, int x) {
heap.push_back(x);
int i = heap.size() - 1;
while (i > 0) {
int p = (i - 1) / 2;
if (heap[i] <= heap[p]) {
break;
}
swap(heap[i], heap[p]);
i = p;
}
}
// functie pentru extragerea elementului maxim din heap
int extract_max(vector<int> &heap) {
int res = heap[0];
heap[0] = heap[heap.size() - 1];
heap.pop_back();
int i = 0;
while (2 * i + 1 < heap.size()) {
int l = 2 * i + 1;
int r = 2 * i + 2;
int j = l;
if (r < heap.size() && heap[r] > heap[l]) {
j = r;
}
if (heap[i] >= heap[j]) {
break;
}
swap(heap[i], heap[j]);
i = j;
}
return res;
}
// functie pentru unirea a doua heap-uri
vector<int> merge_heaps(vector<int> &h1, vector<int> &h2) {
vector<int> res;
for (int x : h1) {
res.push_back(x);
}
for (int x : h2) {
res.push_back(x);
}
make_heap(res.begin(), res.end());
return res;
}
int main() {
ifstream in("mergeheap.in");
ofstream out("mergeheap.out");
int n, q;
in >> n >> q;
vector<vector<int>> heaps(n);
for (int i = 0; i < q; i++) {
int op, m, x, y;
in >> op;
if (op == 1) {
in >> m >> x;
insert(heaps[m - 1], x);
} else if (op == 2) {
in >> m;
int res = extract_max(heaps[m - 1]);
out << res << "\n";
} else if (op == 3) {
in >> x >> y;
heaps[x - 1] = merge_heaps(heaps[x - 1], heaps[y - 1]);
heaps[y - 1].clear();
}
}
in.close();
out.close();
return 0;
}