Pagini recente » Cod sursa (job #506890) | Cod sursa (job #2958331) | Cod sursa (job #1504363) | Cod sursa (job #1029138) | Cod sursa (job #2796695)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("huffman.in");
ofstream fout("huffman.out");
const int NMAX = 1000005;
pair<int, pair<int,int> > rasp[NMAX];
int a[NMAX],st[NMAX],dr[NMAX];
int n,nr,k,sum=0,dim;
queue <int> q1,q2;
void citire(){
fin >> n;
for(int i=1;i<=n;i++){
fin >> nr;
q1.push(i);
a[++k]=nr;
}
}
void add_(int x,int y){
a[++k]=a[x]+a[y];
sum+=a[k];
st[k]=x;
dr[k]=y;
q2.push(k);
}
int minim(){
if(q1.empty()){
int x=q2.front();
q2.pop();
return x;
}
if(q2.empty()){
int x=q1.front();
q1.pop();
return x;
}
if(a[q1.front()]<a[q2.front()]){
int x=q1.front();
q1.pop();
return x;
} else {
int x=q2.front();
q2.pop();
return x;
}
}
void dfs(int poz,int val,int cnt){
if(st[poz]==0 and dr[poz]==0){
rasp[++dim].first=poz;
rasp[dim].second.first=cnt;
rasp[dim].second.second=val;
} else {
dfs(st[poz],2*val,cnt+1);
dfs(dr[poz],2*val+1,cnt+1);
}
}
void solve(){
while(q1.size()+q2.size()>1){
int x=minim();
int y=minim();
add_(x,y);
}
fout << sum << '\n';
dfs(k,0,0);
sort(rasp+1,rasp+dim+1);
for(int i=1;i<=dim;i++){
fout << rasp[i].second.first << ' ' << rasp[i].second.second << '\n';
}
}
int main()
{
citire();
solve();
return 0;
}