Cod sursa(job #1261620)

Utilizator fhandreiAndrei Hareza fhandrei Data 12 noiembrie 2014 16:28:17
Problema Coduri Huffman Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.4 kb
// FMI - Grupa 135 - Semigrupa 2 - Hareza Andrei
// Include
#include <fstream>
#include <queue>
using namespace std;

// Definitii
#define ll long long

#define symbol pair<ll, int>
#define times first
#define posInTree second
#define mp make_pair

#define sons pair<int, int>
#define type_tree pair<ll, sons>
#define value first
#define leftSon second.first
#define rightSon second.second

// Constante
const int sz = 1000001;

// Functii
void dfs(int node, ll currentCode=0, int codeLen=0);

// Variabile
ifstream in("huffman.in");
ofstream out("huffman.out");

int num;
type_tree tree[sz*2];

queue<symbol> firstQueue;
queue<symbol> secondQueue;

ll sum;

// Main
int main()
{
	in >> num;
	for(int i=1 ; i<=num ; ++i)
	{
		in >> tree[i].value;
		firstQueue.push(mp(tree[i].value, i));
	}
	
	int current = num;
	while(firstQueue.size() + secondQueue.size() > 1)
	{
		symbol son1, son2;
		if(firstQueue.empty())
		{
			son1 = secondQueue.front();
			secondQueue.pop();
		}
		else if(secondQueue.empty())
		{
			son1 = firstQueue.front();
			firstQueue.pop();
		}
		else
		{
			if(firstQueue.front().times < secondQueue.front().times)
			{
				son1 = firstQueue.front();
				firstQueue.pop();
			}
			else
			{
				son1 = secondQueue.front();
				secondQueue.pop();
			}	
		}
		
		if(firstQueue.empty())
		{
			son2 = secondQueue.front();
			secondQueue.pop();
		}
		else if(secondQueue.empty())
		{
			son2 = firstQueue.front();
			firstQueue.pop();
		}
		else
		{
			if(firstQueue.front() < secondQueue.front())
			{
				son2 = firstQueue.front();
				firstQueue.pop();
			}
			else
			{
				son2 = secondQueue.front();
				secondQueue.pop();
			}	
		}
		
		tree[++current].value = son1.times + son2.times;
		tree[current].leftSon = son1.posInTree;
		tree[current].rightSon = son2.posInTree;
		
		secondQueue.push(mp(tree[current].value, current));
	}
	
	dfs(current);
	
	out << sum << '\n';
	for(int i=1 ; i<=num ; ++i)
		out << tree[i].leftSon << ' ' << tree[i].value << '\n';
	
	in.close();
	out.close();
	return 0;
}

void dfs(int node, ll currentCode, int codeLen)
{
	if(tree[node].leftSon)
	{
		sum += tree[node].value;
		dfs(tree[node].leftSon, currentCode<<1, codeLen+1);
		dfs(tree[node].rightSon, (currentCode<<1)+1, codeLen+1);
		return;
	}
	
	tree[node].value = currentCode;
	tree[node].leftSon = codeLen;
}