Pagini recente » Cod sursa (job #1564510) | Cod sursa (job #2114655) | Cod sursa (job #1122381) | Cod sursa (job #824127) | Cod sursa (job #398576)
Cod sursa(job #398576)
#include <stdio.h>
#include <deque>
#define N 2000001
using namespace std;
typedef unsigned long long int UL;
int w[N],n;
UL cod[N];
UL niv[N];
struct nod
{int st,dr;
UL w;
nod (int a,int b,UL c)
{st=a;
dr=b;
w=c;
}
nod(){}
}t[2*N];
void df(int poz,UL c,UL nivel)
{cod[poz]=c;
niv[poz]=nivel;
if(poz>n)
{df(t[poz].st,c*2LL,nivel+1LL);
df(t[poz].dr,c*2LL+1LL,nivel+1LL);
}
}
int main ()
{freopen("huffman.in","r",stdin);
freopen("huffman.out","w",stdout);
int i,a,b,min;
scanf("%d",&n);
deque<int> qi;
deque<int> qo;
for (i=1;i<=n;i++)
{scanf("%d",&w[i]);
t[i]=nod(0,0,w[i]);
qi.push_back(i);
}
while(qi.size()+qo.size()>1)
{if(!qi.empty()&&!qo.empty())
{if(t[qi.front()].w<t[qo.front()].w)
{a=qi.front();qi.pop_front();
}
else
{a=qo.front();qo.pop_front();
}
}
else if(!qi.empty())
{a=qi.front();qi.pop_front();
}
else if(!qo.empty())
{a=qo.front();qo.pop_front();
}
if(!qi.empty()&&!qo.empty())
{if(t[qi.front()].w<t[qo.front()].w)
{b=qi.front();qi.pop_front();
}
else
{b=qo.front();qo.pop_front();
}
}
else if(!qi.empty())
{b=qi.front();qi.pop_front();
}
else if(!qo.empty())
{b=qo.front();qo.pop_front();
}
if(!qo.empty())
{if(t[qo.back()].w>t[a].w+t[b].w)
{printf("%d\n",qo.back());
printf("%d\n\n",t[qo.back()].w);
}
// printf("jizz in my pants");
}
t[i]=nod(a,b,t[a].w+t[b].w);
qo.push_back(i);
i++;
}
i--;
df(i,0,0);
UL s=0;
for (i=1;i<=n;i++)
{s+=(UL)w[i]*(UL)niv[i];
}
printf("%lld\n",s);
for (i=1;i<=n;i++)
{printf("%lld %lld\n",niv[i],cod[i]);
}
return 0;
}