Pagini recente » Cod sursa (job #3288872) | Cod sursa (job #3293333) | Cod sursa (job #3292863) | Cod sursa (job #3291821) | Cod sursa (job #3267926)
#include <bits/stdc++.h>
#define inf 1e18 + 1
using namespace std;
const int nmax = 1e6;
queue <int> q1, q2;
long long v[nmax * 2 + 1];
vector <int> g[nmax * 2 + 1];
struct ura
{
long long val, nrb;
}sol[nmax + 1];
long long rez;
int n;
void dfs(int nod, int p, long long val)
{
if(nod <= n)
{
sol[nod].nrb = p;
sol[nod].val = val;
rez += v[nod] * p;
return;
}
dfs(g[nod][0], p + 1, val * 2);
dfs(g[nod][1], p + 1, val * 2 + 1);
}
int getmin()
{
int x = 0, y = 0;
if(!q1.empty())
x = q1.front();
if(!q2.empty())
y = q2.front();
if(x == 0 || v[y] <= v[x])
{
q2.pop();
return y;
}
q1.pop();
return x;
}
int main()
{
freopen("huffman.in", "r", stdin);
freopen("huffman.out", "w", stdout);
ios :: sync_with_stdio(false);
cin.tie(0);
int i, x, y;
long long nr;
cin >> n;
v[0] = inf;
for(i = 1; i <= n; i++)
{
cin >> nr;
q1.push(i);
v[i] = nr;
}
while(q1.size() + q2.size() > 1)
{
x = getmin();
y = getmin();
q2.push(i);
v[i] = v[x] + v[y];
g[i].push_back(x);
g[i].push_back(y);
i++;
}
dfs(n * 2 - 1, 0, 0);
cout << rez << '\n';
for(i = 1; i <= n; i++)
cout << sol[i].nrb << " " << sol[i].val << '\n';
return 0;
}