Pagini recente » Cod sursa (job #2848610) | Cod sursa (job #4724) | Cod sursa (job #375808) | Cod sursa (job #2038096) | Cod sursa (job #2615143)
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream cin("huffman.in");
ofstream cout("huffman.out");
const int NMAX = 1e6;
int N, K;
int nodeWei[NMAX + 2];
long long wei[2 * NMAX + 2];
queue < int > q[3];
int lenChar[NMAX + 2];
long long valChar[NMAX + 2];
vector < pair <int, bool> > g[2 * NMAX + 10];
void dfs(int node, int h, long long valTo)
{
if(node <= N)
{
lenChar[node] = h;
valChar[node] = valTo;
return;
}
for(auto it : g[node])
dfs(it.first, h + 1, (valTo << 1) + it.second);
}
int GetMin()
{
if(q[1].empty())
{
int ind = q[2].front();
q[2].pop();
return ind;
}
if(q[2].empty())
{
int ind = q[1].front();
q[1].pop();
return ind;
}
if(wei[q[1].front()] < wei[q[2].front()])
{
int ind = q[1].front();
q[1].pop();
return ind;
}
int ind = q[2].front();
q[2].pop();
return ind;
}
int main()
{
cin >> N;
K = N;
for(int i = 1; i <= N; i++)
{
cin >> nodeWei[i];
wei[i] = nodeWei[i];
q[1].push(i);
}
if(N == 1)
{
cout << nodeWei[1] << "\n1 0\n";
return 0;
}
while(q[1].size() + q[2].size() > 1)
{
int f = GetMin();
int s = GetMin();
K++;
g[K].push_back({f, 0});
g[K].push_back({s, 1});
long long sumWei = wei[f] + wei[s];
wei[K] = sumWei;
q[2].push(K);
}
dfs(K, 0, 0);
long long totalSz = 0;
for(int i = 1; i <= N; i++)
totalSz = totalSz + 1LL * nodeWei[i] * lenChar[i];
cout << totalSz << '\n';
for(int i = 1; i <= N; i++)
cout << lenChar[i] << ' ' << valChar[i] << '\n';
return 0;
}