# Cod sursa(job #2206943)

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

using namespace std;

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

queue< pair < long, long > > Q, newQ;

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

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

void calcLevel(long long k, long 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)
{
pair < long, long > x1, x2;

if (!newQ.empty() && (Q.empty() || Q.front().first < newQ.front().first))
{
x1 = newQ.front();
newQ.pop();
}
else
{
x1 = Q.front();
Q.pop();
}

if (!newQ.empty() && (Q.empty() || Q.front().first < newQ.front().first))
{
x2 = newQ.front();
newQ.pop();
}
else
{
x2 = Q.front();
Q.pop();
}

long long i = x1.second, j = x2.second;
k++;
node[k].value = - x1.first - x2.first;
node[k].next[0] = i;
node[k].next[1] = j;
newQ.push({-node[k].value, k});
}
root = k;
}

{
f >> n;
for (long long i = 1; i <= n; i++)
{
f >> node[i].value;
node[i].next[0] = node[i].next[1] = 0;
Q.push({-node[i].value, i});
}
}

int main()
{