Pagini recente » Cod sursa (job #2427774) | Cod sursa (job #23281) | Cod sursa (job #874615) | Cod sursa (job #3229290) | Cod sursa (job #2723661)
#include <bits/stdc++.h>
#define ULL unsigned long long
std::ifstream in("huffman.in");
std::ofstream out("huffman.out");
int n;
int coadaP[1000001],lastP=1,vfP,sizeP;
int coadaC[1000001],lastC=1,vfC,sizeC;
ULL val[2000001];
int urm[2000001];
bool muchie[2000001];
ULL Ltot;
int minim()
{
if(!sizeC)
{
sizeP--;
return coadaP[lastP++];
}
else if(!sizeP)
{
sizeC--;
return coadaC[lastC++];
}
else if(val[ coadaP[lastP] ]<=val[ coadaC[lastC] ])
{
sizeP--;
return coadaP[lastP++];
}
else
{
sizeC--;
return coadaC[lastC++];
}
}
int main()
{
in>>n;
for(int i=1;i<=n;i++)
{
in>>val[i];
coadaP[++vfP]=i;
}
sizeP=n;
int i,j,poz=n+1;
while(sizeP+sizeC>=2)
{
i=minim();
j=minim();
urm[i]=poz;
urm[j]=poz;
muchie[j]=1;
val[poz]=val[i]+val[j];
coadaC[++vfC]=poz;
sizeC++;
Ltot+=val[poz];
poz++;
}
out<<Ltot<<'\n';
ULL nr;
int lung;
for(int i=1;i<=n;i++)
{
nr=0,lung=0;
poz=i;
while(urm[poz])
{
nr+=(ULL)muchie[poz]<<lung;
lung++;
poz=urm[poz];
}
out<<lung<<' '<<nr<<'\n';
}
return 0;
}