Cod sursa(job #629599)

Utilizator mihai0110Bivol Mihai mihai0110 Data 3 noiembrie 2011 15:56:57
Problema Coduri Huffman Scor 85
Compilator cpp Status done
Runda Arhiva educationala Marime 1.9 kb
#include <fstream>
#include <iostream>
#include <algorithm>
#include <queue>

#define MAXN 1048576

using namespace std;

long n;
long long result;
long huffman_length[MAXN];
long long huffman_code[MAXN];

typedef struct node {
	struct node *left, *right;
	long weight, info;

	node(long weight, long info) {
		this->weight = weight;
		this->info = info;
		this->left = NULL;
		this->right = NULL;
	}
} Node;

queue<Node*> Q1, Q2;

void read() {
	ifstream f("huffman.in");
	f >> n;
	long x;
	Node *current;
	for(long i = 0; i < n; i++){
		f >> x;
		current = new Node(x, i);
		Q1.push(current);
	}
	f.close();
}

Node* get_smallest_node() {
	Node *ret = NULL;
	Node *node1 = NULL, *node2 = NULL;
	// remove smallest from the two queues
	if (!Q1.empty())
		node1 = Q1.front();
	if (!Q2.empty())
		node2 = Q2.front();

	if (node1 && node2)
		ret = node1->weight < node2->weight ? node1 : node2;
	//assume that none of the queues is empty
	else
		ret = node1 ? node1 : node2;
	if (ret == node1)
		Q1.pop();
	else
		Q2.pop();
	
	return ret;
}

Node* create_huffman() {
	Node *root;
	Node *left, *right;
	while(Q1.size() + Q2.size() != 1) {
		left = get_smallest_node();
		right = get_smallest_node();
		root = new Node(left->weight + right->weight, -1);
		root->left = left;
		root->right = right;
		Q2.push(root);
	}	
	return Q2.front();
}
	
void get_encoding(Node *n, long long code, long len) {
	if (n->info != -1) {
		result += len * n->weight;
		huffman_length[n->info] = len;
		huffman_code[n->info] = code;
		return;
	}
	if (n->left)
		get_encoding(n->left, code * 2, len + 1);
	if (n->right)
		get_encoding(n->right, code * 2 + 1, len + 1);
}

void write_result() {
	ofstream g("huffman.out");
	g << result << "\n";
	for (long i = 0; i < n; i++)
		g << huffman_length[i] << " " << huffman_code[i] << "\n";
	g.close();
}

int main(void) {
	read();
	Node *huffman = create_huffman();
	get_encoding(huffman, 0, 0);
	write_result();
	return 0;
}