Cod sursa(job #1222441)

Utilizator Luncasu_VictorVictor Luncasu Luncasu_Victor Data 23 august 2014 12:20:00
Problema Coduri Huffman Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 kb
#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;
	struct Node *Left, *Right;
	Node() {
		Freq = 0;
		Left = Right = 0;
	}
};
vector<Node*> A;
vector<pair<int, long long> >Sol;
int N;
long long Total;

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) {
		Total += L * A->Freq;
		Sol.push_back(make_pair(L, Code));
	} else {
		DFS(A->Left, L+1, Code);
		DFS(A->Right, L+1, (1<<L) + Code);
	}
}

int main() {

	f >> N;
	A.resize(N);
	for (int i = 0; i < N; i++) {
		A[i] = new Node();
		f >> A[i]->Freq;
	}
	
	Huffman();
	DFS(A[0], 0, 0);
	
	g << Total << endl;
	for (int i = 0; i < Sol.size(); i++) {
		g << Sol[i].first << " " << Sol[i].second << "\n";
	}
	
	return 0;
}