Pagini recente » Cod sursa (job #448909) | Cod sursa (job #1435385) | Cod sursa (job #1854679) | Cod sursa (job #1097931) | Cod sursa (job #1759869)
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <queue>
#define N 1000000
using namespace std;
struct nod{
long long val;
int ord;
struct nod *left=NULL, *right=NULL;
};
queue <struct nod> qfr,qin;
long long v[N],s;
int l[N];
void gen( nod *x , long long vcod, int lvl ){
if(x->ord==0){
s+=x->val;
}
v[ x->ord ]=vcod;
l[ x->ord ]=lvl;
if(x->left==NULL && x->right==NULL){
return;
}else{
if(x->left!=NULL){
gen(x->left,2*vcod,lvl+1);
}
if(x->right!=NULL){
gen(x->right,2*vcod+1,lvl+1);
}
}
}
int main(){
struct nod nodx;
int i,x,n;
bool spy=0;
freopen("huffman.in","r",stdin);
freopen("huffman.out","w",stdout);
scanf("%d",&n);
for(i=1;i<=n;i++){
scanf("%d",&x);
nodx.val=x;
nodx.ord=i;
qfr.push(nodx);
}
while( !(qfr.size()==0 && qin.size()==1) ){
nod *a=new nod;
nod *b=new nod;
nod *c=new nod;
for(i=0;i<2;i++){
if(qfr.empty() && qin.empty()){
spy=1;
break;
}
if(qfr.empty()){
*b=*a;
*a=qin.front(); qin.pop();
}else if(qin.empty()){
*b=*a;
*a=qfr.front(); qfr.pop();
}else{
if(qfr.front().val > qin.front().val ){
*b=*a;
*a=qin.front(); qin.pop();
}else{
*b=*a;
*a=qfr.front(); qfr.pop();
}
}
}
if(spy==1){
qin.push(*a);
break;
}
c->val=a->val+b->val;
c->ord=0;
c->left=b; c->right=a;
qin.push(*c);
}
nodx=qin.front();
gen(&nodx,0,0);
printf("%lld\n",s);
for(i=1;i<=n;i++){
printf("%d %lld\n",l[i],v[i]);
}
return 0;
}