Pagini recente » Cod sursa (job #2002789) | Cod sursa (job #2077643) | Cod sursa (job #1886918) | Cod sursa (job #2017254) | Cod sursa (job #2001509)
#include <iostream>
#include <cstdio>
#include <queue>
#define NMAX 2000005
using namespace std;
int n, nAux;
long long sol, dist[NMAX];
pair <long long, long long> tati[NMAX];
queue <pair <long long, long long> >q1, q2;
void read()
{
scanf("%d", &n);
nAux = n;
long long x;
for(int i=1; i<=n; ++i)
{
scanf("%lld", &x);
q1.push(make_pair(x, i));
}
}
pair <long long, long long> minim()
{
pair <long long, long long> x;
if(q1.empty())
{
x=q2.front();
q2.pop();
return x;
}
if(q2.empty())
{
x=q1.front();
q1.pop();
return x;
}
if(q1.front() <= q2.front())
{
x=q1.front();
q1.pop();
return x;
}
else
{
x=q2.front();
q2.pop();
return x;
}
}
void codare()
{
pair <long long, long long> x1, x2;
while(q1.size() + q2.size() > 1)
{
x1 = minim();
x2 = minim();
q2.push(make_pair(x1.first + x2.first, ++n));
sol += x1.first + x2.first;
tati[(int)x1.second].first = tati[(int)x2.second].first = n;
tati[(int)x1.second].second = 0;
tati[(int)x2.second].second = 1;
}
}
void afisare()
{
printf("%lld\n", sol);
for(int i=n-1; i>=1; i--)
{
tati[i].second|=(1LL*(tati[tati[i].first].second<<1));
dist[i]=1+dist[tati[i].first];
}
for(int i=1;i<=nAux;i++)
{
printf("%lld %lld\n",dist[i],tati[i].second);
}
}
int main()
{
freopen("huffman.in", "r", stdin);
freopen("huffman.out", "w", stdout);
read();
codare();
afisare();
return 0;
}