# Cod sursa(job #2206931)

Utilizator Data 24 mai 2018 15:52:05 Coduri Huffman 30 cpp done Arhiva educationala 1.46 kb
``````#include <iostream>
#include <fstream>
#include <queue>
#include <string>
#define NMAX 1000005

using namespace std;

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

priority_queue< pair < long long, int > > Q;

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

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

void calcLevel(int k, int 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() >= 2)
{
pair < long long, int > x1, x2;
x1 = Q.top();
Q.pop();
x2 = Q.top();
Q.pop();
int i = x1.second, j = x2.second;
k++;
node[k].value = - x1.first - x2.first;
node[k].next[0] = i;
node[k].next[1] = j;
Q.push({-node[k].value, k});
}
root = Q.top().second; // root = 2 * n - 1;
}

{
f >> n;
for (int 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()
{