Cod sursa(job #885065)

Utilizator howsiweiHow Si Wei howsiwei Data 21 februarie 2013 16:46:25
Problema Coduri Huffman Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <deque>
#include <cstring>
#include <cstdlib>
#include <cassert>
using namespace std;
typedef unsigned long long ull;

struct node {
	node() { data=-1; freq=1<<30; }
	node * child[2];
	ull 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[1]->freq;
	}
	return b.front();
}

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

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<ull> code(n);
	ull len=0;
	store(code, root, 1ull, len);
	fout << len-root.freq << '\n';
	for (int i=0; i<n; ++i) {
		//fout << code[i].length() << ' ' << strtoll(code[i].c_str(),NULL,2) << '\n';
		unsigned int tmp=63-__builtin_clzll(code[i]);
		fout << tmp << ' ' << (code[i]^(1ull<<tmp)) << '\n';
	}
	return 0;
}