Pagini recente » Cod sursa (job #2616740) | Cod sursa (job #787440) | Cod sursa (job #585569) | Cod sursa (job #1065064) | Cod sursa (job #2615150)
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream cin("huffman.in");
ofstream cout("huffman.out");
const int NMAX = 1e6;
int N, K;
long long wei[2 * NMAX + 2];
queue < int > q[3];
int lenChar[NMAX + 2];
long long valChar[NMAX + 2];
pair <int, bool> g[2 * NMAX + 10][2];
void dfs(int node, int h, long long valTo)
{
if(node <= N)
{
lenChar[node] = h;
valChar[node] = valTo;
return;
}
for(int i = 0; i < 2; i++)
{
pair <int, bool> it = g[node][i];
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 >> wei[i];
q[1].push(i);
}
if(N == 1)
{
cout << wei[1] << "\n1 0\n";
return 0;
}
while(q[1].size() + q[2].size() > 1)
{
int f = GetMin();
int s = GetMin();
K++;
g[K][0] = {f, 0};
g[K][1] = {s, 1};
wei[K] = wei[f] + wei[s];
q[2].push(K);
}
dfs(K, 0, 0);
long long totalSz = 0;
for(int i = 1; i <= N; i++)
totalSz = totalSz + 1LL * wei[i] * lenChar[i];
cout << totalSz << '\n';
for(int i = 1; i <= N; i++)
cout << lenChar[i] << ' ' << valChar[i] << '\n';
return 0;
}