# Cod sursa(job #370923)

Utilizator Data 2 decembrie 2009 19:27:44 Coduri Huffman Ascuns cpp done 1.49 kb
``````// Huffman cu doua cozi, O(n)

#include <stdio.h>

using namespace std;

#define maxn 1000100
#define inf 1LL * 1000000000 * 1000000000

struct nod
{
long long v;
long f[2];
} nod[2*maxn];

long n, i, j, k, p, l[2], r[2];
long q[2][maxn], lg[maxn];
long long b[maxn], m, sol;

void df(long poz, long long cod, long nivel)
{
if(nod[poz].f[0])
{
df(nod[poz].f[0], cod*2, nivel+1);
df(nod[poz].f[1], cod*2+1, nivel+1);
return;
}
lg[poz]=nivel;
b[poz]=cod;
}

void solve()
{
k=n;
l[0]=l[1]=1;
r[0]=n;
while(l[0]+l[1]<=r[0]+r[1])
{
++k;
for(j=0; j<2; j++)
{
p=0;
m=inf;
for(i=0; i<2; i++)
{
if(nod[q[i][l[i]]].v<m && l[i]<=r[i])
{
p=i;
m=nod[q[i][l[i]]].v;
}
}
nod[k].f[j]=q[p][l[p]];
nod[k].v+=nod[q[p][l[p]]].v;
l[p]++;
}
sol+=nod[k].v;
q[1][++r[1]]=k;
}
df(k, 0, 0);
}

int main()
{
freopen("huffman.in", "r", stdin);
freopen("huffman.out", "w", stdout);
scanf("%d", &n);
for(i=1; i<=n; i++)
{
scanf("%d", &nod[i].v);
q[0][i]=i;
}
solve();
printf("%lld\n", sol);
for(i=1; i<=n; i++)
{
printf("%d %lld\n", lg[i], b[i]);
}
return 0;
}

``````