Pagini recente » Cod sursa (job #2597489) | Cod sursa (job #2597536) | Cod sursa (job #2597495) | Cod sursa (job #2597488) | Cod sursa (job #1998977)
#include<cstdio>
#include<queue>
const int NMAX = 1000002;
using namespace std;
struct node
{
int parent;
bool bit;
} nodes[NMAX * 2 + 1];
int N;
queue<int> Q;
queue<int> lQ;
int len[NMAX];
long long code[NMAX];
long long vals[2 * NMAX + 1];
long long ans_sum;
int pop_min ()
{
int ans;
if (lQ.empty())
{
ans = Q.front();
Q.pop();
return ans;
}
if (Q.empty())
{
ans = lQ.front();
lQ.pop();
return ans;
}
if (vals[lQ.front()] <= vals[Q.front()])
{
ans = lQ.front();
lQ.pop();
return ans;
}
else
{
ans = Q.front();
Q.pop();
return ans;
}
}
int main()
{
freopen("huffman.in", "r", stdin);
freopen("huffman.out", "w", stdout);
int val;
scanf("%d", &N);
for (int i = 0; i < N; ++i)
{
lQ.push(i);
scanf("%d", vals + i);
}
int node_count = N;
while(lQ.size() + Q.size() > 1)
{
int first = pop_min();
int second = pop_min();
ans_sum += vals[node_count] = vals[first] + vals[second];
nodes[second].bit = 1;
nodes[first].parent = nodes[second].parent = node_count;
Q.push(node_count++);
}
printf("%lld\n", ans_sum);
for (int i = node_count - 2; i >= 0; --i)
{
code[i] = (code[nodes[i].parent] << 1) | nodes[i].bit;
len[i] = len[nodes[i].parent] + 1;
}
for (int i = 0; i < N; ++i) {
printf("%d %lld\n", len[i], code[i]);
}
}