Pagini recente » Cod sursa (job #2486228) | Cod sursa (job #36480) | Cod sursa (job #31218) | Cod sursa (job #1444818) | Cod sursa (job #1334110)
#include<stdio.h>
#include<fstream>
using namespace std;
struct nod{
long long v;
int f[2];
}a[10000010];
long n,q[1000100][2],l[2],r[2];
long long sum[1000100],sol=0,lg[1000010];
void df(int x,int cod,int nivel){
if(a[x].f[0]){
df(a[x].f[0],cod*2+1,nivel+1);
df(a[x].f[1],cod*2,nivel+1);
return;
}
sum[x]=cod;
lg[x]=nivel;
sol += nivel*a[x].v;
}
int main(){
freopen("huffman.in","r",stdin);
ofstream o("huffman.out");
scanf("%d",&n);
for(int i=1;i<=n;i++)scanf("%d",&a[i].v),q[i][0]=i;
int k=n;
l[0]=l[1]=1;
r[0]=n;
while(l[0]+l[1]<=r[1]+r[0]){
k++;
for(int i=0;i<2;i++){
int p=0;
long long m=1000000000000000;
for(int j=0;j<2;j++){
if(l[j]<=r[j]&&m>a[q[l[j]][j]].v){
p=j;
m=a[q[l[j]][j]].v;
}
}
a[k].v+=m;
a[k].f[i]=q[l[p]][p];
l[p]++;
}
q[++r[1]][1]=k;
}
df(k,0,0);
o<<sol<<"\n";
for(int i=1;i<=n;i++)o<<lg[i]<<" "<<sum[i]<<"\n";
}