Cod sursa(job #549873)

Utilizator ProcopliucProcopliuc Adrian Procopliuc Data 9 martie 2011 00:04:35
Problema Coduri Huffman Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 kb
# include <fstream>
# define inf 1LL*1000000000*1000000000
using namespace std;
ifstream f ("huffman.in");
ofstream g ("huffman.out");
long long int lb[1000005],lg,ff,x;
int l[1000005],n,vf,i,j;

struct nod 
{
	long long int ap;
	int info;
	nod *st,*dr;
}*p,*v,*q;

class coada
{
	int pr,ul;
	nod *c[1000005];
public:
	coada (){pr=1;ul=0;}
	void push (nod *p);
	void pop (nod *&p);
	long long int appr ();

}c1,c2;


	void coada::push (nod *p)
	{
		ul++;
		c[ul]=p;
	}
	
	void coada::pop (nod *&p)
	{
		p=c[pr];
		pr++;
	}
	
	inline long long int coada::appr ()
	{
		if (pr<=ul)
		return c[pr]->ap;
		else
			return inf;
	}
	
	
	
	void df (nod *p)
	{
		vf++;
		
		if (p->st)
		{	
			
			x<<=1;
			df (p->st);
			
			
		}
		if (p->dr)
		{	
		
			x<<=1;
			x+=1;
			df (p->dr);
		}
		if (p->st==0 && p->dr==0)
		{
			l[p->info]=vf-1;
			lb[p->info]=x;
			
		}
		else
			lg+=p->ap;
		vf--;
		x>>=1;
		
	}
		
	
	
int main ()
{
	
	f>>n;
	for (i=1;i<=n;i++)
	{
		f>>x;
		p=new nod;
		p->info=i;
		p->ap=x;
		p->st=0;
		p->dr=0;
		c1.push (p);
	}
	for (i=1;i<n;i++)
	{
		p=new nod;
		p->ap=0;
		for (j=1;j<=2;j++)
		if (c1.appr()<c2.appr())
		{
			c1.pop (q);
			if (j==1)
			p->st=q;
			else
				p->dr=q;
			p->ap+=q->ap;
		}
		else
		{
			c2.pop (q);
			if (j==1)
			p->st=q;
			else
				p->dr=q;
			p->ap+=q->ap;
		}
		
		
		c2.push (p);
	}
	
	v=p;
	x=0;
	ff=1;
	df (v);
	g<<lg<<"\n";
	for (i=1;i<=n;i++)
	g<<l[i]<<" "<<lb[i]<<"\n";
	return 0;
}