Pagini recente » Cod sursa (job #648816) | Cod sursa (job #1783457) | Cod sursa (job #696297) | Cod sursa (job #2668230) | Cod sursa (job #1674581)
#include<bits/stdc++.h>
using namespace std;
typedef struct lol {
int st,dr;
}troll;
const long long INF=1e18+69;
int i,n,q[2][2000005],curr,gmb,fnc,rsl[1000005];
long long rs,rsc[1000005],a[2000005];
troll c1,c2,arb[2000005];
int get_next() {
int x,y;
if(c1.st>c1.dr) x=0; else x=q[0][c1.st];
if(c2.st>c2.dr) y=0; else y=q[1][c2.st];
if(a[x]<a[y])
{
++c1.st;
return x;
}
++c2.st;
return y;
}
void get_results(int poz,int lung,long long val) {
if(poz<=n) rsl[poz]=lung,rsc[poz]=val,rs+=1LL*lung*a[poz];
else {
get_results(arb[poz].st,lung+1,2*val);
get_results(arb[poz].dr,lung+1,2*val+1);
}
}
int main()
{
ifstream cin("huffman.in");
ofstream cout("huffman.out");
ios_base::sync_with_stdio(0); cin.tie(0);
cin>>n; c1.st=c2.st=1; a[0]=INF;
for(i=1;i<=n;++i) cin>>a[i],q[0][++c1.dr]=i;
for(curr=n,i=1;i<n;++i)
{
gmb=get_next(); fnc=get_next();
arb[++curr].st=gmb; arb[curr].dr=fnc;
a[curr]=a[gmb]+a[fnc]; q[1][++c2.dr]=curr;
}
get_results(curr,0,0);
cout<<rs<<'\n';
for(i=1;i<=n;++i) cout<<rsl[i]<<' '<<rsc[i]<<'\n';
return 0;
}