Pagini recente » Cod sursa (job #1181069) | Cod sursa (job #2280473) | Cod sursa (job #2738946) | Cod sursa (job #2180197) | Cod sursa (job #2495275)
#include <bits/stdc++.h>
#define dim 1000004
#define inf 9223372036854775807
#define mod 9973
using namespace std;
ifstream fin("huffman.in");
ofstream fout("huffman.out");
long long niv,H[dim];
long long C[dim];
long long n,st,st2,dr,i,N;
unsigned long long total;
pair <long long , pair<int,int> > v[2*dim+10];
void dfs(int nod,long long cod)
{
/// v[nod].second.first si v[nod].second.second vecini
niv++;
//cout<<nod<<"-"<<cod<<" "<<niv<<endl;
if(nod<=N)
{
H[nod]=niv;
C[nod]=cod;
total+=niv*v[nod].first;
}
else
{
dfs(v[nod].second.first,2LL*cod);
dfs(v[nod].second.second,2LL*cod+1);
}
niv--;
}
int main()
{
fin>>n;
N=n;
for(i=1; i<=n; i++)
{
fin>>v[i].first;
v[i+n].first=inf;
}
st=1;
st2=n+1;
dr=n;
while(dr<2*n-1)
{
if(st+1<=n&&v[st+1].first<=v[st2].first)
{
/// 2 din stanga
v[++dr].first=v[st].first+v[st+1].first;
v[dr].second= {st,st+1};
// cout<<st<<" "<<st+1<<" "<<dr<<endl;
st+=2;
continue;
}
if(st2+1<=dr&&v[st2+1].first<=v[st].first)
{
/// 2 din dreapta
v[++dr].first=v[st2].first+v[st2+1].first;
v[dr].second= {st2,st2+1};
// cout<<st2<<" "<<st2+1<<" "<<dr<<endl;
v[st2].first=v[st2+1].first=inf;
st2+=2;
continue;
}
/// 1-1
v[++dr].first=v[st].first+v[st2].first;
v[st2].first=inf;
v[dr].second={st,st2};
// cout<<st<<" "<<st2+1<<" "<<dr<<endl;
st++;
st2++;
}
niv--;
dfs(2*n-1,0);
fout<<total<<"\n";
for(i=1;i<=n;i++){
fout<<H[i]<<" "<<C[i]<<"\n";
}
}