Cod sursa(job #598098)

Utilizator sima_cotizoSima Cotizo sima_cotizo Data 24 iunie 2011 15:59:04
Problema Coduri Huffman Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include <vector>
#include <queue>
#include <cstdio>
using namespace std;
#define MAX 1000010

struct node
{
	node *left, *right;
	int c, weight;
};

class comparator
{
public:
	bool operator()(node* A, node* B)
	{
		return A->weight >= B->weight; // sau ">" ?
	}
};

priority_queue<node*, vector<node*>, comparator> Q;
int code[MAX], length[MAX], total, N;

void df(node *r, int c, int d)
{
	if ( r->c > 0 )
	{
		code[r->c] = c;
		length[r->c] = d;
		total += r->weight * d;
		return ;
	}
	if ( r->left )
		df(r->left, c << 1, d+1);
	if ( r->right )
		df(r->right, (c << 1) + 1, d+1);
}

int main()
{
	freopen("huffman.in", "r", stdin);
	freopen("huffman.out", "w", stdout);

	scanf("%d", &N);
	for (int i=1; i<=N; ++i)
	{
		node *p = new node;
		scanf("%d", &p->weight);
		p->c = i;
		p->left = p->right = NULL;
		Q.push(p);
	}

	while ( Q.size() > 1 )
	{
		node *a = Q.top(); Q.pop();
		node *b = Q.top(); Q.pop();

		node *c = new node;
		c -> weight = a->weight + b->weight;
		c -> c = -1;
		c -> left = a;
		c -> right = b;
		Q.push(c);
	}

	node *root = Q.top(); Q.pop();
	df(root, 0, 0);

	printf("%d\n", total);
	for (int i=1; i<=N; ++i)
	{
		printf("%d %d", length[i], code[i]);
		
/*		printf(" = ");
		if ( code[i] == 0 )
			printf("0");
		for (int j=1; j<=code[i]; j<<=1)
			printf("%d", code[i] & j ? 1 : 0);
*/
		printf("\n");
	}
	return 0;
}