Pagini recente » Profil EMS12 | Profil Sham3 | Profil user_name | Profil BigNote21 | Cod sursa (job #3314413)
#include <bits/stdc++.h>
using namespace std;
#define i32 int32_t
#define i64 int64_t
static constexpr i32 MAX = 1'000'000;
int main() {
#ifndef LOCAL
freopen("huffman.in", "r", stdin);
freopen("huffman.out", "w", stdout);
#endif
ios::sync_with_stdio(false);
cin.tie(nullptr);
struct Node {
i64 v{};
i32 next[2]{};
};
static Node tree[2 * MAX + 5];
i32 N;
if (!(cin >> N)) {
return 1;
}
if (N == 1) {
i64 x;
if (!(cin >> x)) {
return 1;
}
cout << 0 << '\n' << 1 << ' ' << 0 << '\n';
return 0;
}
for (i32 i = 1; i <= N; ++i) {
if (!(cin >> tree[i].v)) {
return 1;
}
}
i64 X = 0;
vector<i32> Q1(N + 2);
for (i32 i = 1; i <= N; ++i) {
Q1[i] = i;
}
i32 L1 = 1, R1 = N;
vector<i32> Q2(N + 2);
i32 L2 = 1, R2 = 0;
i32 nextIdx = N;
for (; (R1 - L1 + 1) + (R2 - L2 + 1) > 1;) {
++nextIdx;
tree[nextIdx].v = 0;
for (int j = 0; j < 2; ++j) {
i32 pick;
if (L1 <= R1 && (L2 > R2 || tree[Q1[L1]].v <= tree[Q2[L2]].v)) {
pick = Q1[L1++];
} else {
pick = Q2[L2++];
}
tree[nextIdx].next[j] = pick;
tree[nextIdx].v += tree[pick].v;
}
Q2[++R2] = nextIdx;
X += tree[nextIdx].v;
}
i32 root = Q2[R2];
vector<i32> L(N + 1);
vector<i64> B(N + 1);
auto dfs = [&](auto self, i32 i, i64 x, i32 h) -> void {
if (tree[i].next[0] || tree[i].next[1]) {
self(self, tree[i].next[0], x << 1, h + 1);
self(self, tree[i].next[1], (x << 1) | 1, h + 1);
} else if (i <= N) {
L[i] = h;
B[i] = x;
}
};
dfs(dfs, root, 0, 0);
cout << X << '\n';
for (i32 i = 1; i <= N; ++i) {
cout << L[i] << ' ' << B[i] << '\n';
}
return 0;
}