Pagini recente » Cod sursa (job #1532017) | Cod sursa (job #1772784) | Cod sursa (job #1906876) | Cod sursa (job #1281453) | Cod sursa (job #2517664)
#include <bits/stdc++.h>
#define Val first
#define Poz second
using namespace std;
ifstream in("huffman.in");
ofstream out("huffman.out");
int n,vf;
priority_queue <pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> c;
struct compresie
{
string cod;
int val;
int st=0,dr=0;
};
vector <compresie> huf;
int main()
{
in>>n;
vf=n;
huf.resize(n*2+1);
for(int i=1;i<=n;i++)
{
in>>huf[i].val;
c.push({huf[i].val,i});
}
while(!c.empty())
{
pair <int,int> nod1,nod2;
nod1=c.top();c.pop();
nod2=c.top();c.pop();
huf[++vf].val=nod1.Val+nod2.Val;
huf[vf].st=nod1.Poz;
huf[vf].dr=nod2.Poz;
if(!c.empty())
c.push({huf[vf].val,vf});
}
for(int i=vf;i>=n+1;i--)
{
int nod1=huf[i].st;
int nod2=huf[i].dr;
huf[nod1].cod=huf[i].cod+'0';
huf[nod2].cod=huf[i].cod+'1';
}
long long sum=0;
for(int i=1;i<=n;i++)
sum+=huf[i].val*huf[i].cod.size();
out<<sum<<'\n';
for(int i=1;i<=n;i++)
{
int lung=huf[i].cod.size();
long long nr=0;
for(int j=0;j<=lung-1;j++)
if(huf[i].cod[lung-1-j]=='1')
nr+=(1<<j);
out<<lung<<' '<<nr<<'\n';
}
return 0;
}