Cod sursa(job #671092)
using namespace std;
#include<iostream>
#include<fstream>
#include<queue>
int N;
struct nod{
int eu,l,r,lg;
long long s;};
nod v[2000010];
long long q[2000010];
int R;
ofstream fout("huffman.out");
int min(int &s1,int &s2,int k)
{
if((q[s1]<q[s2] && s1<=N)||s2>=k)
{
s1++;
return s1-1;
}
else
{
s2++;
return s2-1;
}
}
nod unite(int i1,int i2,int k)
{
q[k]=q[i1]+q[i2];
nod a;
//cout<<q[k]<<" "<<k<<" "<<i1<<" "<<i2<<"\n";
a.eu=k;
a.l=i1;
a.r=i2;
return a;
}
void create()
{
int k=N;
int s1=1,s2=k+1;
long long ans=0;
long long dummy1,dummy2;
q[s2]=0x3f3f3f3f;
while(s1<=N || s2<k)
{
k++;
dummy1=min(s1,s2,k);
dummy2=min(s1,s2,k);
//cout<<k<<" "<<dummy1<<" "<<dummy2<<"\n";
v[k]=unite(dummy1,dummy2,k);//vezi ordinea
ans+=q[k];
}
R=k;
fout<<ans<<"\n";
}
void cit()
{
ifstream fin("huffman.in");
fin>>N;
int i;
for(i=1;i<=N;i++)
{
fin>>q[i];
}
fin.close();
}
void dfs(int x,long long sum,int lev)
{
if(v[x].l==0)
{
v[x].lg=lev;
v[x].s=sum;
return;
}
else
{
dfs(v[x].l,sum*2,lev+1);
dfs(v[x].r,sum*2+1,lev+1);
}
}
int main()
{
cit();
create();
dfs(R,0,0);
for(int i=1;i<=N;i++)
{
fout<<v[i].lg<<" "<<v[i].s<<"\n";
}
fout.close();
return 0;
}