Pagini recente » Cod sursa (job #1443980) | Cod sursa (job #2756693) | Cod sursa (job #1553262) | Cod sursa (job #1383621) | Cod sursa (job #1143135)
#include<fstream>
#include<iostream>
#define Maxn 1000100
#define INF 1LL*Maxn*Maxn
using namespace std;
struct nod {long long valoare;int fii[2];}Nod[2*Maxn];
int N,p, l[2], r[2],NrNod;
int q[2][Maxn], lg[Maxn];
long long b[Maxn], m, sol;
void citire() {
ifstream in("huffman.in");
int i;
in>>N;
for(i=1;i<=N;i++) {
in>>Nod[i].valoare;
q[0][i]=i;
}
in.close();
}
void dfs(int poz, long long cod, int nivel)
{
if(Nod[poz].fii[0]) {
dfs(Nod[poz].fii[0], cod*2, nivel+1);
dfs(Nod[poz].fii[1], cod*2+1, nivel+1);
return;
}
lg[poz]=nivel;
b[poz]=cod;
}
void solve() {
int i,j;
NrNod=N;
l[0]=1;
l[1]=1;
r[0]=N;
while(l[0]+l[1]<=r[0]+r[1]) {
NrNod++;
for(j=0;j<=1;++j) {
p=0;
m=INF;
for(i=0;i<=1;++i) {
if(Nod[q[i][l[i]]].valoare<m && l[i]<=r[i]) {
p=i;
m=Nod[q[i][l[i]]].valoare;
}
}
Nod[NrNod].fii[j]=q[p][l[p]];
Nod[NrNod].valoare+=Nod[q[p][l[p]]].valoare;
l[p]++;
}
sol+=Nod[NrNod].valoare;
q[1][++r[1]]=NrNod;
}
dfs(NrNod,0,0);
}
void afisare() {
ofstream out("huffman.out");
int i;
out<<sol<<'\n';
for(i=1;i<=N;i++)
out<<lg[i]<<' '<<b[i]<<'\n';
out.close();
}
int main() {
citire();
solve();
afisare();
return 0;
}