Pagini recente » Cod sursa (job #1728191) | Cod sursa (job #2792898) | Cod sursa (job #2041058) | Cod sursa (job #1923545) | Cod sursa (job #601890)
Cod sursa(job #601890)
#include<fstream.h>
#define N 2000001
typedef struct nod
{long info,val;
nod *st,*dr;}Nod;
long long lg=0,q2[N];
long n,i,j,k,t;
unsigned int q1[N];
Nod *p[N],*l;
Nod *make(long x,long y,Nod *left,Nod *right)
{Nod *r=new Nod;
r->info=x;
r->val=y;
r->st=left;
r->dr=right;
return r;}
int main()
{ifstream f1("huffman.in");
ofstream f2("huffman.out");
f1>>n;
for(i=1;i<=n;i++)
{f1>>q1[i];
q2[i]=N;
p[i]=make(q1[i],i,NULL,NULL);}
j=k=1,t=0;
for(i=1;i<n;i++)
if(k<=n)
{if(q1[k+1]<=q2[j]&&k+1<=n)
{q2[++t]=q1[k]+q1[k+1];
p[t+n]=make(q2[t],t+n,p[k],p[k+1]);
k+=2;}
else
if(q2[j+1]<=q1[k])
{q2[++t]=q2[j]+q2[j+1];
p[t+n]=make(q2[t],t+n,p[j+n],p[j+1+n]);
j+=2;}
else
if(q2[j]<=q1[k]&&q1[k]<=q2[j+1])
{q2[++t]=q1[k]+q2[j];
p[t+n]=make(q2[t],t+n,p[j+n],p[k]);
j++;
k++;}
else
if(q1[k]<=q2[j]&&((q2[j]<=q1[k+1]&&k+1<=n)||k+1>n))
{q2[++t]=q1[k]+q2[j];
p[t+n]=make(q2[t],t+n,p[k],p[j+n]);
j++;
k++;}
lg+=q2[t];}
else
{q2[++t]=q2[j]+q2[j+1];
lg+=q2[t];
p[t+n]=make(q2[t],t+n,p[j+n],p[j+1+n]);
j+=2;}
f2<<lg<<"\n";
l=p[t+n];
k=t=0;
p[t++]=l;
q2[l->val]=q1[l->val]=0;
while(k<t)
{l=p[k++];
if(l->st)
{q1[l->st->val]=q1[l->val]+1;
q2[l->st->val]=2*q2[l->val];
p[t++]=l->st;}
if(l->dr)
{q1[l->dr->val]=q1[l->val]+1;
q2[l->dr->val]=2*q2[l->val]+1;
p[t++]=l->dr;}}
for(i=1;i<=n;i++)
f2<<q1[i]<<" "<<q2[i]<<"\n";
f1.close();
f2.close();
return 0;}