Cod sursa(job #754260)
#include <cstring>
#include <fstream>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
const int SIZE = 1000002;
int N, F[SIZE];
queue<int> Q[2];
int nodnow;
long long val[2 * SIZE], son[2 * SIZE][2];
long long res[SIZE][2], result;
void Dfs(int nod, long long val, long long len)
{
if (son[nod][0])
{
Dfs(son[nod][0], val * 2, len + 1);
Dfs(son[nod][1], val * 2 + 1, len + 1);
return;
}
res[nod][0] = len;
res[nod][1] = val;
}
int main()
{
ifstream fin("huffman.in");
freopen("huffman.out", "w", stdout);
fin >> N;
for (int i = 1; i <= N; ++i)
{
fin >> F[i];
Q[0].push(i);
val[i] = F[i];
}
nodnow = N;
while (Q[0].size() + Q[1].size() > 1)
{
++nodnow;
for (int i = 0; i < 2; ++i)
{
int now = -1, where;
for (int j = 0; j < 2; ++j)
if (!Q[j].empty() && (now == -1 || val[now] > val[Q[j].front()]))
{
now = Q[j].front();
where = j;
}
Q[where].pop();
val[nodnow] += val[now];
son[nodnow][i] = now;
}
Q[1].push(nodnow);
}
Dfs(nodnow, 0, 0);
for (int i = 1; i <= N; ++i)
result += F[i] * res[i][0];
printf("%lld\n", result);
for (int i = 1; i <= N; ++i)
printf("%lld %lld\n", res[i][0], res[i][1]);
fin.close();
}