Pagini recente » Cod sursa (job #371013) | Cod sursa (job #690031) | Cod sursa (job #115376) | Cod sursa (job #959915) | Cod sursa (job #1923145)
#include <cstdio>
#include <queue>
using namespace std;
struct node{
long long cost;
int son[2];
}node[2000000];
int N, tag, numberOfBits[1000001], index;
long long decimalValue[1000001], textLength, maximum;
queue<int> Q[2];
void DFS(int tag, long long code, int level){
if(node[tag].son[0]){
DFS(node[tag].son[0], code * 2, level + 1);
DFS(node[tag].son[1], code * 2 + 1, level + 1);
}else{
numberOfBits[tag] = level;
decimalValue[tag] = code;
}
}
int main(){
freopen("huffman.in", "r", stdin);
freopen("huffman.out", "w", stdout);
scanf("%d", &N);
for(int i = 1; i <= N; i++){
scanf("%d", &node[i].cost);
Q[0].push(i);
}
for(tag = N + 1;; tag++){
for(int i = 0; i < 2; i++){
index = 0; maximum = 1LL << 47;
for(int j = 0; j < 2; j++){
if(!Q[j].empty() && (node[Q[j].front()].cost < maximum)){
index = j;
maximum = node[Q[j].front()].cost;
}
}
node[tag].son[i] = Q[index].front();
node[tag].cost += node[Q[index].front()].cost;
Q[index].pop();
}
textLength += node[tag].cost;
Q[1].push(tag);
if(Q[0].empty() && Q[1].size() == 1) break;
}
DFS(tag, 0, 0);
printf("%lld\n", textLength);
for(int i = 1; i <= N; i++){
printf("%d %lld\n", numberOfBits[i], decimalValue[i]);
}
return 0;
}