Pagini recente » Cod sursa (job #1936921) | Cod sursa (job #2661059) | Cod sursa (job #765732) | Cod sursa (job #3167417) | Cod sursa (job #2640311)
#include <bits/stdc++.h>
using namespace std;
const int NMAX = 2000005;
int N;
pair <int, long long> q1[NMAX], q2[NMAX];
int son[2][NMAX];
int h[NMAX];
long long v[NMAX];
void dfs(int node, int father = 0)
{
h[node] = h[father] + 1;
if (son[0][node] != 0 && son[1][node] != 0)
{
v[son[0][node]] = 2LL * v[node];
v[son[1][node]] = 2LL * v[node] + 1;
dfs(son[0][node], node);
dfs(son[1][node], node);
}
}
int main()
{
ifstream fin("huffman.in");
ofstream fout("huffman.out");
fin >> N;
for (int i = 1;i <= N;++i)
{
q1[i].first = i;
fin >> q1[i].second;
}
int pos = 1, left = 1, right = 0;
int step = N;
long long answer = 0;
for (int i = 1;i < N;++i)
{
pair <int, long long> a, b;
if (left > right || (pos <= N && q1[pos].second < q2[left].second))
a = q1[pos++];
else
a = q2[left++];
if (left > right || (pos <= N && q1[pos].second < q2[left].second))
b = q1[pos++];
else
b = q2[left++];
++step;
son[0][step] = a.first;
son[1][step] = b.first;
q2[++right] = make_pair(step, a.second + b.second);
answer += a.second + b.second;
}
h[0] = -1;
dfs(step);
fout << answer << "\n";
for (int i = 1;i <= N;++i)
fout << h[i] << " " << v[i] << "\n";
fin.close();
fout.close();
return 0;
}