Cod sursa(job #1065830)

Utilizator ELHoriaHoria Cretescu ELHoria Data 23 decembrie 2013 18:49:56
Problema Coduri Huffman Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.68 kb
#include <fstream>
#include <queue>

using namespace std; 

struct Node {
	Node *leftSon;
	Node *rightSon;
	long long weight;
	Node(Node *ls ,Node *rs,long long w) {
		leftSon = ls;
		rightSon = rs;
		weight = w;
	}
};

inline void rev(int &val,int l) {
	for (int i = 0;i <=  (l >> 1);i++) {
		if ( ((val >> i ) & 1) != ((val >> (l - i - 1)) & 1) ) {
			val ^= (1 << i);
			val ^= (1 << (l - i - 1));
		}
	}
}

void print(Node *node,int code,int depth,ostream &cout) {
	if (node -> leftSon == NULL && node -> rightSon == NULL) {
		rev(code,depth);
		cout << depth << " " << code << "\n";
		return;
	}

	if (node -> leftSon != NULL) {
		print(node -> leftSon,code,depth + 1,cout);
	}

	if (node -> rightSon != NULL) {
		print(node -> rightSon,code | 1 << depth,depth + 1,cout);
	}
	
}

int main()
{
	ifstream cin("huffman.in");
	ofstream cout("huffman.out");
    queue< Node* > Q[2];
	int n, w;
	long long ans = 0;
	cin >> n;
	for (int i = 0;i < n;i++) {
		cin >> w;
		Q[0].push(new Node(NULL,NULL,w));
	}

	Node *root;
	while (Q[0].size() + Q[1].size() > 1) {
		Node *node[2];
		for (int k = 0;k < 2;k++) {
			if (!Q[0].empty() && !Q[1].empty()) {
				if (Q[0].front()->weight < Q[1].front()->weight) {
					node[k] = Q[0].front();
					Q[0].pop();
				} else {
					node[k] = Q[1].front();
					Q[1].pop();
				}
			} else 
			if (!Q[0].empty()) {
				node[k] = Q[0].front();
				Q[0].pop();
			} else {
				node[k] = Q[1].front();
				Q[1].pop();
			}
		}

		root = new Node(node[0],node[1],node[0]->weight + node[1]->weight);
		ans += root->weight;
		Q[1].push(root);
	}

	cout << ans<< "\n";
	print(root,0,0,cout);
	return 0;
}