Pagini recente » Cod sursa (job #2020516) | Cod sursa (job #275497) | Cod sursa (job #1675130) | Cod sursa (job #1203067) | Cod sursa (job #900665)
Cod sursa(job #900665)
#include<cstdio>
#include<queue>
#define INF 1000005
using namespace std;
struct nod
{
int f,ind;
nod *st,*dr;
};
struct cmp
{
bool operator()(const nod* n1,const nod* n2)
{
return n1->f>n2->f;
}
};
priority_queue<nod*, vector<nod*>,cmp > Q;
int n,freq[INF];
unsigned long long lg=0,ras[INF][2];
void df(nod *nd,int nr,int level)
{
if(nd==NULL)return;
if(nd->ind!=-1)
{
ras[nd->ind][0]=level;
ras[nd->ind][1]=nr;
lg+=freq[nd->ind]*level;
return;
}
df(nd->st,nr*2,level+1);
df(nd->dr,nr*2+1,level+1);
}
int main()
{
freopen("huffman.in","r",stdin);
freopen("huffman.out","w",stdout);
scanf("%d",&n);
for(int i=0;i<n;++i)
{
scanf("%d",&freq[i]);
nod *nd=new nod;
nd->f=freq[i];nd->ind=i;
Q.push(nd);
}
while(Q.size()>1)
{
nod *nd1=Q.top();
Q.pop();
nod *nd2=Q.top();
Q.pop();
nod *nd3=new nod;
nd3->ind=-1;
nd3->f=nd1->f+nd2->f;
if(nd1->f<nd2->f)
{
nd3->st=nd1;
nd3->dr=nd2;
}
else
{
nd3->st=nd2;
nd3->dr=nd1;
}
Q.push(nd3);
}
df(Q.top(),0,0);
printf("%lld\n",lg);
for(int i=0;i<n;++i)
printf("%lld %lld\n",ras[i][0],ras[i][1]);
return 0;
}