Pagini recente » Cod sursa (job #733575) | Cod sursa (job #223001) | Cod sursa (job #155685) | Cod sursa (job #1771966) | Cod sursa (job #1222450)
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
#define MAX 1000010
ifstream f("huffman.in");
ofstream g("huffman.out");
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, (1<<L) + Code);
DFS(A->Right, L+1, Code);
}
}
int main() {
f >> N;
A.resize(N);
V.resize(N);
for (int i = 0; i < N; i++) {
A[i] = new Node();
f >> A[i]->Freq;
V[i] = A[i];
}
Huffman();
DFS(A[0], 0, 0);
g << Sol << endl;
for (int i = 0; i < V.size(); i++) {
g << V[i]->L << " " << V[i]->Code << "\n";
}
return 0;
}