Cod sursa(job #1222471)

Utilizator Luncasu_VictorVictor Luncasu Luncasu_Victor Data 23 august 2014 13:15:01
Problema Coduri Huffman Scor 65
Compilator cpp Status done
Runda Arhiva educationala Marime 1.5 kb
#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;
}