Cod sursa(job #1998882)

Utilizator FlameingoAiordachioaei Marius Flameingo Data 9 iulie 2017 15:08:25
Problema Coduri Huffman Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 kb
#include<cstdio>
#include<queue>

const int NMAX = 1000002;
using namespace std;

struct node
{
    int parent;
    bool bit;
} nodes[NMAX * 2 + 1];

int N;
queue<int> Q;

int len[NMAX];
unsigned long long code[NMAX];
unsigned long long vals[2 * NMAX + 1];
int queue_front;
unsigned long long ans_sum;
int pop_min ()
{
    int ans;
    if (queue_front == N) {
        ans = Q.front();
        Q.pop();
        return ans;
    }
    if (Q.empty()) {
        ans = queue_front;
        ++queue_front;
        return ans;
    }
    int lqf = queue_front;
    int qf = Q.front();
    if (vals[lqf] <= vals[qf])
    {
        ++queue_front;
        return lqf;
    }
    else
    {
        Q.pop();
        return qf;
    }
}

int main()
{
    freopen("huffman.in", "r", stdin);
    freopen("huffman.out", "w", stdout);
    int val;

    scanf("%d", &N);
    for (int i = 0; i < N; ++i)
    {
        int val;
        scanf("%d", &val);
        vals[i] = val;
    }
    int node_count = N;
    while(queue_front < N || Q.size() != 1)
    {
        int first = pop_min();
        int second = pop_min();
        vals[node_count] = vals[first] + vals[second];
        ans_sum += vals[node_count];
        nodes[first].bit = 0;
        nodes[second].bit = 1;
        nodes[first].parent = node_count;
        nodes[second].parent = node_count;
        Q.push(node_count);
        node_count++;
    }

    for (int i = node_count - 2; i >= 0; --i)
    {
        code[i] = code[nodes[i].parent] * 2 + nodes[i].bit;
        len[i] = len[nodes[i].parent] + 1;
    }

    printf("%llu\n", ans_sum);
    for (int i = 0; i < N; ++i) {
        printf("%d %llu\n", len[i], code[i]);
    }

}