Pagini recente » Cod sursa (job #495871) | Cod sursa (job #940064) | Profil M@2Te4i | Profil M@2Te4i | Cod sursa (job #972632)
Cod sursa(job #972632)
#include <cstdio>
#include <vector>
#define In "huffman.in"
#define Out "huffman.out"
#define min(a,b) ((a)<(b)?(a):(b))
#define LL long long
#define PLLN pair < LL , node* >
#define PLI pair < LL , int >
#define Nmax 1000010
using namespace std;
struct node
{
node *l, *r;
int ind;
node()
{
ind = 0;
l = r = NULL;
}
};
PLI sol[Nmax];
node *Root = new node;
PLLN A[Nmax];
PLLN B[Nmax];
int N, LA, LB,indA,indB;
LL Sum;
inline void Read()
{
freopen(In,"r",stdin);
freopen(Out,"w",stdout);
scanf("%d",&N);
int x;
node *X;
for(int i = 1;i <= N ; ++i)
{
scanf("%d",&x);
X = new node;
X->ind = i;
A[++LA] = make_pair(x,X);
}
}
inline PLLN Min()
{
PLLN X;
X.first = 0;
if(indA>LA && indB>LB)
return X;
if(indA>LA)
return B[indB++];
if(indB>LB)
return A[indA++];
if(A[indA] < B[indB])
return A[indA++];
return B[indB++];
}
inline void BuildTree()
{
PLLN X, Y;
node *A,*Last;
indA = indB = 1;
while(true)
{
X = Min();
Y = Min();
if(X.first<=0 || Y.first<=0)
{
Root = Last;
return;
}
A = new node;
A->l = X.second;
A->r = Y.second;
Sum += X.first+Y.first;
Last = A;
B[++LB] = make_pair(X.first+Y.first,A);
}
}
inline void BuildSol(node *_node,const LL X, const int length)
{
if(_node->ind)
{
sol[_node->ind].first = X;
sol[_node->ind].second = length;
return;
}
if(_node->l)
BuildSol(_node->l,(X<<1),length+1);
if(_node->r)
BuildSol(_node->r,(X<<1)+1,length+1);
}
inline void Write()
{
printf("%I64d\n",Sum);
for(int i = 1;i <= N; ++i)
printf("%d %I64d\n",sol[i].second,sol[i].first);
printf("\n");
}
int main()
{
Read();
BuildTree();
BuildSol(Root,0,0);
Write();
return 0;
}