Pagini recente » Cod sursa (job #1247157) | Cod sursa (job #2790968) | Cod sursa (job #1211227) | Cod sursa (job #2781925) | Cod sursa (job #2281390)
#include <fstream>
#include <queue>
using namespace std;
ifstream fin ("huffman.in");
ofstream fout ("huffman.out");
int nr[2000001], n, a, st[2000001], dr[2000001], total;
int nod[1000001], nrnod, x1, x2;
int p[1000001], g[1000001];
auto cmp = [](int x, int y) {
return (nr[x] > nr[y]);
};
priority_queue <int, vector<int>, decltype(cmp)> pq(cmp);
void check(int node, int grad, int prod) {
if (!st[node]) {
total += nr[node] * grad;
g[node] = grad;
p[node] = prod;
}
else {
check(st[node], grad + 1, prod * 2);
check(dr[node], grad + 1, prod * 2 + 1);
}
}
int main() {
fin >> n;
for (int i = 1; i <= n; ++i) {
fin >> a;
nod[i] = ++nrnod;
nr[nod[i]] = a;
pq.push(nod[i]);
}
while (!pq.empty()) {
x1 = pq.top();
pq.pop();
// fout << x1 << ' ' << nr[x1] << '\n';
if (!pq.empty()) {
x2 = pq.top();
pq.pop();
nr[++nrnod] = nr[x1] + nr[x2];
pq.push(nrnod);
st[nrnod] = x1;
dr[nrnod] = x2;
}
}
check(nrnod, 0, 0);
fout << total << '\n';
for (int i = 1; i <= n; ++i)
fout << g[i] << ' ' << p[i] << '\n';
}