Pagini recente » Cod sursa (job #169841) | Cod sursa (job #1650033) | Cod sursa (job #2111256) | Cod sursa (job #1295574) | Cod sursa (job #1222471)
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
#define MAX 1000010
struct Node {
int Freq, L;
long long Code;
struct Node *Left, *Right;
Node() {
L = 0;
Code = 0;
Freq = 0;
Left = Right = 0;
}
};
vector<Node*> A, V;
int N;
long long Sol;
bool FreqSort(Node *A, Node *B) {
return A->Freq > B->Freq;
}
void Huffman() {
Node *X, *Y, *Z;
make_heap(A.begin(), A.end(), FreqSort);
while (A.size() > 1) {
X = A[0];
pop_heap(A.begin(), A.end(), FreqSort);
A.pop_back();
Y = A[0];
pop_heap(A.begin(), A.end(), FreqSort);
A.pop_back();
Z = new Node();
Z->Freq = X->Freq + Y->Freq;
Z->Left = X;
Z->Right = Y;
A.push_back(Z);
push_heap(A.begin(), A.end(), FreqSort);
}
}
void DFS(Node *X, int L, long long Code) {
Node *A = X;
if (A->Left == 0 && A->Right == 0) {
A->L = L;
A->Code = Code;
Sol += A->L * A->Freq;
} else {
DFS(A->Left, L+1, (Code<<1));
DFS(A->Right, L+1, (Code<<1) + 1);
}
}
int main() {
freopen("huffman.in","r",stdin);
freopen("huffman.out","w",stdout);
scanf("%d", &N);
A.resize(N);
V.resize(N);
for (int i = 0; i < N; i++) {
A[i] = new Node();
scanf("%d", &A[i]->Freq);
V[i] = A[i];
}
Huffman();
DFS(A[0], 0, 0);
printf("%lld\n", Sol);
for (int i = 0; i < V.size(); i++) {
printf("%d %lld\n", V[i]->L, V[i]->Code);
}
return 0;
}