Pagini recente » Cod sursa (job #500673) | Cod sursa (job #2932257) | Cod sursa (job #745725) | Cod sursa (job #2665622) | Cod sursa (job #2627858)
#include <fstream>
#include <queue>
using namespace std;
ifstream cin("huffman.in");
ofstream cout("huffman.out");
typedef long long ll;
const ll lim=1e6+3;
ll cod[lim],f[lim];
int depth[lim];
queue<pair<ll,int> > q0,q1;
pair<int,int> vec[2*lim];
int n;
ll ans,lung;
void df(int x,ll ad,ll c)
{
if(x<=n)
{
depth[x]=ad;
cod[x]=c;
ans+=depth[x]*f[x];
return ;
}
df(vec[x].first,ad+1,2*c);
df(vec[x].second,ad+1,2*c+1);
}
int main()
{
cin>>n;
if(n==1)
{
cin>>lung;
cout<<lung<<'\n';
cout<<"1 0\n";
return 0;
}
for(int i=1;i<=n;++i)
{
cin>>lung;
f[i]=lung;
q0.push({lung,i});
}
int nod=n;
int nx,ny;
ll x,y;
while(1)
{
if(q0.empty())
{
x=q1.front().first;
nx=q1.front().second;
q1.pop();
if(q1.empty())
break;
y=q1.front().first;
ny=q1.front().second;
q1.pop();
++nod;
vec[nod]={nx,ny};
q1.push({x+y,nod});
}
else if(q1.empty())
{
x=q0.front().first;
nx=q0.front().second;
q0.pop();
y=q0.front().first;
ny=q0.front().second;
q0.pop();
++nod;
vec[nod]={nx,ny};
q1.push({x+y,nod});
}
else
{
if(q0.front()<q1.front())
{
x=q0.front().first;
nx=q0.front().second;
q0.pop();
}
else
{
x=q1.front().first;
nx=q1.front().second;
q1.pop();
}
if(q1.empty())
{
y=q0.front().first;
ny=q0.front().second;
q0.pop();
}
else if(q0.empty())
{
y=q1.front().first;
ny=q1.front().second;
q1.pop();
}
else
{
if(q0.front()<q1.front())
{
y=q0.front().first;
ny=q0.front().second;
q0.pop();
}
else
{
y=q1.front().first;
ny=q1.front().second;
q1.pop();
}
}
++nod;
vec[nod]={nx,ny};
q1.push({x+y,nod});
}
}
df(nod,0,0);
cout<<ans<<'\n';
for(int i=1;i<=n;++i)
cout<<depth[i]<<' '<<cod[i]<<'\n';
return 0;
}