Cod sursa(job #720130)

Utilizator iuli1505Parasca Iuliana iuli1505 Data 22 martie 2012 13:15:31
Problema Coduri Huffman Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 kb
#include<cstdio>
#include<deque>
#include<utility>
#include<algorithm>
#include<vector>
#define nmax 1000001
using namespace std;
int n,i,nr;
long long val,L;
struct tree
{
	long long inf, nod,cod,l;
	tree *st, *dr;
	tree()
	{
		inf=0;
		nod=0;
		cod=0;
		l=0;
		st=0;
		dr=0;
	}
};
deque<tree> v;
pair<long long, long long>sol[nmax];
tree *r,*x,*y;
int crit(tree a, tree b)
{
	if(a.inf<b.inf)
		return 1;
	return 0;
}
int main()
{
	freopen("huffman.in","r",stdin);
	freopen("huffman.out","w",stdout);
	scanf("%d", &n);
	for(i=1;i<=n;i++)
	{
		scanf("%lld", &val);
		r=new tree;
		r->inf=val;
		r->nod=i;
		v.push_back(*r);
	}
	for(i=1;i<n;i++)
	{
		x=new tree;
		y=new tree;
		*x=v.front();
		v.pop_front();
		*y=v.front();
		v.pop_front();
		r=new tree;
		r->inf=x->inf+y->inf;
		L+=r->inf;
		r->st=x;
		r->dr=y;
		v.insert(lower_bound(v.begin(),v.end(),*r,crit),*r);
	}
	printf("%lld\n", L);
	for(;!v.empty();)
	{
		*r=v.front();
		v.pop_front();
		if(r->st==0)
			continue;
		x=r->st;
		y=r->dr;
		x->l=r->l+1;
		y->l=r->l+1;
		x->cod=r->cod*2;
		y->cod=r->cod*2+1;
		if(x->nod)
		{
			sol[x->nod].first=x->l;
			sol[x->nod].second=x->cod;
		}
		if(y->nod)
		{
			sol[y->nod].first=y->l;
			sol[y->nod].second=y->cod;
		}
		v.push_back(*x);
		v.push_back(*y);
	}
	for(i=1;i<=n;i++)
		printf("%lld %lld\n", sol[i].first, sol[i].second);
	return 0;
}