Pagini recente » Cod sursa (job #13349) | Cod sursa (job #1845644) | Cod sursa (job #2406004) | Cod sursa (job #757703) | Cod sursa (job #1046971)
#include<cstdio>
#include<deque>
#define oo (1LL<<62)
#define NMAX 1000000+5
using namespace std;
int N,M;
int V[NMAX],L[NMAX];
int St[2*NMAX],Dr[2*NMAX];
long long S[NMAX],Lg;
deque<pair<long long,int> > A,B;
void DFS(int x,int l,long long s)
{
if(x<=N)
{
L[x]=l;
S[x]=s;
Lg+=L[x]*V[x];
return;
}
if(St[x]) DFS(St[x],l+1,2*s);
if(Dr[x]) DFS(Dr[x],l+1,2*s+1);
}
int main()
{
int i,cnt,StN,DrN;
long long X,Y,StV,DrV;
freopen("huffman.in","r",stdin);
freopen("huffman.out","w",stdout);
scanf("%d",&N);
for(i=1;i<=N;i++)
{
scanf("%d",&V[i]);
A.push_back(make_pair(V[i],i));
}
M=N;
for(cnt=N-1;cnt;--cnt)
{
if(!A.empty()) X=A.front().first;
else X=oo;
if(!B.empty()) Y=B.front().first;
else Y=oo;
if(X<Y)
{
StV=X;
StN=A.front().second;
A.pop_front();
}
else
{
StV=Y;
StN=B.front().second;
B.pop_front();
}
if(!A.empty()) X=A.front().first;
else X=oo;
if(!B.empty()) Y=B.front().first;
else Y=oo;
if(X<Y)
{
DrV=X;
DrN=A.front().second;
A.pop_front();
}
else
{
DrV=Y;
DrN=B.front().second;
B.pop_front();
}
M++;
St[M]=StN; Dr[M]=DrN;
B.push_back(make_pair(StV+DrV,M));
}
DFS(M,0,0LL);
printf("%lld\n",Lg);
for(i=1;i<=N;i++) printf("%d %lld\n",L[i],S[i]);
return 0;
}