Pagini recente » Cod sursa (job #1105079) | Cod sursa (job #2362691) | Cod sursa (job #160136) | Cod sursa (job #163929) | Cod sursa (job #2920100)
#include <bits/stdc++.h>
#define int long long
using namespace std;
ifstream fin ("huffman.in");
ofstream fout("huffman.out");
const int dim=2e6+9;
int n,cost_total;
int cost[dim];
signed len[dim];
int cod[dim];
signed l[dim],r[dim];
queue<int>q1,q2;
void dfs(int nod,int cod_curent,int lungime_curenta){
len[nod]=lungime_curenta;
cod[nod]=cod_curent;
if(l[nod]&&r[nod]){
dfs(l[nod],cod_curent*2 ,lungime_curenta+1);
dfs(r[nod],cod_curent*2+1,lungime_curenta+1);
}else{
cost_total+=cost[nod]*lungime_curenta;
}
}
signed main(){
fin>>n;
for(int i=1;i<=n;i++){
fin>>cost[i];
q1.push(i);
}
int nr=n;
while(q1.size()+q2.size()>=2){
int x,y;
if(q1.empty() || (!q2.empty() && cost[q1.front()]>cost[q2.front()])){
x=q2.front();
q2.pop();
}else{
x=q1.front();
q1.pop();
}
if(q1.empty() || (!q2.empty() && cost[q1.front()]>cost[q2.front()])){
y=q2.front();
q2.pop();
}else{
y=q1.front();
q1.pop();
}
nr++;
l[nr]=x,r[nr]=y;
cost[nr]=cost[x]+cost[y];
q2.push(nr);
}
dfs(2*n-1,0,0);
fout<<cost_total<<'\n';
for(int i=1;i<=n;i++){
fout<<len[i]<<' '<<cod[i]<<'\n';
}
}