Cod sursa(job #884970)

Utilizator howsiweiHow Si Wei howsiwei Data 21 februarie 2013 15:30:01
Problema Coduri Huffman Scor 5
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <deque>
#include <cstring>
#include <cstdlib>
using namespace std;

struct node {
	node() { data=-1; freq=1<<30; }
	node * child[2];
	int freq;
	int data;
};

node hufftree(deque<node> a) {
	deque<node> b;
	while (!a.empty() || b.size()>1) {
		b.push_back(node());
		for (int i=0; i<2; ++i) {
			b.back().child[i]=new node;
			if (a.empty() ||  b.front().freq < a.front().freq) {
				*b.back().child[i]=b.front();
				b.pop_front();
			}
			else {
				*b.back().child[i]=a.front();
				a.pop_front();
			}
		}
		b.back().freq = b.back().child[0]->freq + b.back().child[0]->freq;
	}
	return b.front();
}

void store(vector<string> & code, node tmp, string s) {
	if (tmp.data!=-1) {
		code[tmp.data]=s;
		return;
	}
	store(code,*tmp.child[0],s+'0');
	store(code,*tmp.child[1],s+'1');
}

int main() {
	ifstream fin("huffman.in");
	ofstream fout("huffman.out");
	int n; fin >> n;
	deque<node> a(n);
	for (int i=0; i<n; ++i) {
		a[i].data=i;
		fin >> a[i].freq;
	}
	node root=hufftree(a);
	vector<string> code(n);
	store(code, root, "");
	int len=0;
	for (int i=0; i<n; ++i) len+=a[i].freq*code[i].length();
	fout << len << '\n';
	for (int i=0; i<n; ++i) {
		fout << code[i].length() << /*' ' << code[i] << */' ' << strtol(code[i].c_str(),NULL,2) << '\n';
	}
	return 0;
}