Cod sursa(job #1503131)

Utilizator stefanzzzStefan Popa stefanzzz Data 15 octombrie 2015 16:44:52
Problema Coduri Huffman Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
#include <stdio.h>
#include <iostream>
#define MAXN 1000005
using namespace std;

struct Node {
    long long val;
    int sons[2];
} tree[2 * MAXN];

int nt, x;
pair<int, long long> sol[MAXN];
int n, ind1 = 1, ind2;

int extractMin() {
    if(ind1 > n || (ind2 <= nt && tree[ind2].val < tree[ind1].val)) {
        ++ind2;
        return ind2 - 1;
    }

    ++ind1;
    return ind1 - 1;
}

void DFS(int u, int lvl, long long vl) {
    if(tree[u].sons[0] == 0 && tree[u].sons[1] == 0) {
        sol[u] = make_pair(lvl, vl);
        return;
    }
    if(tree[u].sons[0])
        DFS(tree[u].sons[0], lvl + 1, vl << 1);
    if(tree[u].sons[1])
        DFS(tree[u].sons[1], lvl + 1, (vl << 1) + 1);
}

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

    scanf("%d", &n);
    for(int i = 1; i <= n; i++) {
        scanf("%d", &x);
        tree[++nt].val = x;
    }
    ind2 = n + 1;

    for(int i = 1; i < n; i++) {
        int x1 = extractMin();
        int x2 = extractMin();

        tree[++nt].val = tree[x1].val + tree[x2].val;
        tree[nt].sons[0] = x1;
        tree[nt].sons[1] = x2;
    }

    DFS(nt, 0, 0);

    long long totLg = 0;
    for(int i = 1; i <= n; i++)
        totLg += 1LL * sol[i].first * tree[i].val;
    printf("%lld\n", totLg);

    for(int i = 1; i <= n; i++)
        printf("%d %lld\n", sol[i].first, sol[i].second);

    return 0;
}