Mai intai trebuie sa te autentifici.
Cod sursa(job #2517661)
| Utilizator | Data | 3 ianuarie 2020 22:12:23 | |
|---|---|---|---|
| Problema | Coduri Huffman | Scor | 30 |
| Compilator | cpp-64 | Status | done |
| Runda | Arhiva educationala | Marime | 1.35 kb |
#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';
}
int 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();
int 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;
}
