Cod sursa(job #754257)

Utilizator darrenRares Buhai darren Data 1 iunie 2012 11:26:12
Problema Coduri Huffman Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.18 kb
#include <fstream>
#include <algorithm>
#include <queue>
#include <vector>

using namespace std;

const int SIZE = 1000002;

int N, F[SIZE];
queue<int> Q[2];
int nodnow;
int val[2 * SIZE], son[2 * SIZE][2];
int res[SIZE][2], result;

void Dfs(int nod, int val, int len)
{
	if (son[nod][0])
	{
		Dfs(son[nod][0], val * 2, len + 1);
		Dfs(son[nod][1], val * 2 + 1, len + 1);
		return;
	}
	res[nod][0] = len;
	res[nod][1] = val;
}

int main()
{
	ifstream fin("huffman.in");
	ofstream fout("huffman.out");
	
	fin >> N;
	for (int i = 1; i <= N; ++i)
	{
		fin >> F[i];
		Q[0].push(i);
		val[i] = F[i];
	}
	
	nodnow = N;
	while (Q[0].size() + Q[1].size() > 1)
	{
		++nodnow;
		for (int i = 0; i < 2; ++i)
		{
			int now = -1, where;
			for (int j = 0; j < 2; ++j)
				if (!Q[j].empty() && (now == -1 || val[now] > val[Q[j].front()]))
				{
					now = Q[j].front();
					where = j;
				}
			Q[where].pop();
			
			val[nodnow] += val[now];
			son[nodnow][i] = now;
		}
		
		Q[1].push(nodnow);
	}
	Dfs(nodnow, 0, 0);
	
	for (int i = 1; i <= N; ++i)
		result += F[i] * res[i][0];
	fout << result << '\n';
	for (int i = 1; i <= N; ++i)
		fout << res[i][0] << ' ' << res[i][1] << '\n';
	
	fin.close();
	fout.close();
}