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