# Cod sursa(job #2206948)

Utilizator Data 24 mai 2018 16:24:08 Coduri Huffman 70 cpp done Arhiva educationala 1.79 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <string>
#define NMAX 1000005

using namespace std;

ifstream f("huffman.in");
ofstream g("huffman.out");

queue< long > Q, newQ;

struct Node
{
long long value;
long next[2];
}node[2*NMAX];

long n, k, root, level[2 * NMAX];
long long cod[2 * NMAX], lg;

void calcLevel(long k, long nivel, long long c)
{
level[k] = nivel;
cod[k] = c;
if (node[k].next[0] != 0)
{
calcLevel(node[k].next[0], nivel + 1, 2 * c);
calcLevel(node[k].next[1], nivel + 1, 2 * c + 1);
}
}

void solve()
{
k = n;

while (Q.size() + newQ.size() >= 2)
{
long x1, x2;

if (!newQ.empty() && (Q.empty() || node[Q.front()].value >  node[newQ.front()].value))
{
x1 = newQ.front();
newQ.pop();
}
else
{
x1 = Q.front();
Q.pop();
}

if (!newQ.empty() && (Q.empty() || node[Q.front()].value >  node[newQ.front()].value))
{
x2 = newQ.front();
newQ.pop();
}
else
{
x2 = Q.front();
Q.pop();
}

k++;
node[k].value = node[x1].value + node[x2].value;
lg += node[k].value;
node[k].next[0] = x1;
node[k].next[1] = x2;
newQ.push(k);
}
root = k;
}

void read()
{
f >> n;
for (int i = 1; i <= n; i++)
{
f >> node[i].value;
node[i].next[0] = node[i].next[1] = 0;
Q.push(i);
}
}

int main()
{
read();
solve();
calcLevel(root, 0, 0);

long long sum = 0;
//for (int i = 1; i <= n; i++)
//sum += node[i].value * level[i];
g << lg <<'\n';

for (int i = 1; i <= n; i++)
g << level[i] << ' ' << cod[i] << '\n';
return 0;
}