Pagini recente » Cod sursa (job #340248) | Cod sursa (job #1618973) | Cod sursa (job #349673) | Cod sursa (job #2630937) | Cod sursa (job #2516482)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("huffman.in");
ofstream fout("huffman.out");
#define int long long
const int DIM = 2e6;
int to[DIM + 7][2];
int cnt[DIM + 7];
int len[DIM + 7];
int base[DIM + 7];
queue <int> q[3];
int getMin()
{
int x;
if(q[1].empty())
{
x = q[2].front();
q[2].pop();
return x;
}
if(q[2].empty())
{
x = q[1].front();
q[1].pop();
return x;
}
if(cnt[q[1].front()] <= cnt[q[2].front()])
{
x = q[1].front();
q[1].pop();
return x;
}
x = q[2].front(); q[2].pop();
return x;
}
void dfs(int nod, int val, int l)
{
if(!to[nod][0])
{
len[nod] = l;
base[nod] = val;
return;
}
for(int i = 0; i < 2; i++)
dfs(to[nod][i], (val << 1) + i, l + 1);
}
main()
{
int n;
fin >> n;
int it = n;
for(int i = 1; i <= n; i++)
{
fin >> cnt[i];
q[1].push(i);
}
int total = 0;
while((q[1].size() + q[2].size()) != 1)
{
int x = getMin();
int y = getMin();
q[2].push(++it);
cnt[it] = cnt[x] + cnt[y];
total += cnt[it];
to[it][0] = x, to[it][1] = y;
}
fout << total << '\n';
dfs(it, 0, 0);
for(int i = 1; i <= n; i++)
fout << len[i] << " " << base[i] << '\n';
}