Pagini recente » Cod sursa (job #1478806) | Cod sursa (job #234878) | Cod sursa (job #342187) | Cod sursa (job #3247457) | Cod sursa (job #3291538)
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
#define pii pair<int, int>
#define x first
#define y second
const int KMAX = 20;
const char nl = '\n';
vector<vector<int>> a(KMAX + 5);
int pos[KMAX + 5];
class MinHeap {
private:
vector<pii> heap;
void heapify_up(int index) {
int parent = (index - 1) / 2;
if (index > 0 && heap[index].x < heap[parent].x) {
swap(heap[index], heap[parent]);
heapify_up(parent);
}
}
void heapify_down(int index) {
while (true) {
int left = 2 * index + 1;
int right = 2 * index + 2;
int smallest = index;
if (left < heap.size() && heap[left].x < heap[smallest].x)
smallest = left;
if (right < heap.size() && heap[right].x < heap[smallest].x)
smallest = right;
if (smallest == index)
return;
swap(heap[index], heap[smallest]);
index = smallest;
}
}
public:
void push(int value, int vector_index) {
heap.push_back({value, vector_index});
heapify_up(heap.size() - 1);
}
pii pop() {
pii top = heap.front();
heap[0] = heap.back();
heap.pop_back();
if (!heap.empty()) {
heapify_down(0);
}
return top;
}
bool empty() const {
return heap.empty();
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
freopen("interclasari.in", "r", stdin);
freopen("interclasari.out", "w", stdout);
int k;
cin >> k;
int total = 0;
for (int i = 1; i <= k; ++i) {
int n;
cin >> n;
total += n;
a[i].resize(n);
for (int j = 0; j < n; ++j) {
cin >> a[i][j];
}
pos[i] = 0;
}
MinHeap heap;
for (int i = 1; i <= k; ++i) {
if (!a[i].empty()) {
heap.push(a[i][0], i);
pos[i] = 1;
}
}
cout << total << nl;
for (int i = 0; i < total; ++i) {
pii top = heap.pop();
cout << top.x << ' ';
int s = top.y;
if (pos[s] < a[s].size()) {
heap.push(a[s][pos[s]], s);
pos[s]++;
}
}
cout << nl;
return 0;
}