Pagini recente » Cod sursa (job #869135) | Cod sursa (job #871498) | Cod sursa (job #1667705) | Cod sursa (job #1112383) | Cod sursa (job #1239858)
#include <cstdio>
#include <vector>
#include <algorithm>
#define tip long long
using namespace std;
struct huffman
{
huffman *l,*r;
tip val;
huffman()
{
l=r=NULL;
val=1000000000000000010;
}
}*huff,*x,*y,*a[5000000][2];
tip n,i,top1,top2,front1,front2,sol,q,aq,sc,lg;
bool poz,ok;
vector<pair<tip,tip>>v;
void run(huffman *nod)
{
if(nod->l==NULL)
{
v.push_back(make_pair(lg,sc));
return;
}
if(nod->l)
{
sc<<=1;
lg++;
run(nod->l);
sc>>=1;lg--;
}
if(nod->r)
{
sc<<=1;
sc++;
lg++;
run(nod->r);
sc>>=1;lg--;
}
}
int main()
{
freopen("huffman.in","r",stdin);
freopen("huffman.out","w",stdout);
scanf("%lld",&n);
for(i=1;i<=n;i++)
{
scanf("%lld",&q);
huff=new huffman;
huff->val=q;
a[i][0]=huff;
}
a[1][1]=new huffman;
top1=n;
front1=front2=top2=1;
poz=1;
while(top1-front1+top2-front2>=2)
{
if(a[front2][poz]==NULL)a[front2][poz]=new huffman;
if(a[front1][!poz]==NULL)a[front1][!poz]=new huffman;
if(a[front2][poz]->val<a[front1][!poz]->val)
x=a[front2++][poz];
else
x=a[front1++][!poz];
if(a[front2][poz]==NULL)a[front2][poz]=new huffman;
if(a[front1][!poz]==NULL)a[front1][!poz]=new huffman;
if(a[front2][poz]->val<a[front1][!poz]->val)
y=a[front2++][poz];
else
y=a[front1++][!poz];
huff=new huffman;
sol+=x->val+y->val;
huff->val=x->val+y->val;
huff->l=x;
huff->r=y;
a[top2++][poz]=huff;
if(top1<front1)
{
aq=top1;
a[aq][!poz]=new huffman;
poz=!poz;
top1=top2;
front1=front2;
top2=front2=aq;
}
}
printf("%lld\n",sol);
run(huff);
sort(v.begin(),v.end());
for(vector<pair<tip,tip>>::iterator it=v.end()-1;it>=v.begin();it--)
printf("%lld %lld\n",it->first,it->second);
return 0;
}