Cod sursa(job #2470897)

Utilizator IulianOleniucIulian Oleniuc IulianOleniuc Data 9 octombrie 2019 20:55:57
Problema Coduri Huffman Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.68 kb
#include <bits/stdc++.h>
using namespace std;

// #include <queue>
// #include <vector>
// #include <utility>
// #include <fstream>

// using std::pair;
// using std::make_pair;

// using std::queue;
// using std::vector;

std::ifstream fin("huffman.in");
std::ofstream fout("huffman.out");

void dfs(int node, int len, int64_t code, vector<pair<int, int>> tree, vector<pair<int, int64_t>>& sol) {
    if (!tree[node].first) {
        sol[node] = make_pair(len, code);
        return;
    }
    dfs(tree[node].first, len + 1, code * 2, tree, sol);
    dfs(tree[node].second, len + 1, code * 2 + 1, tree, sol);
}

int main() {
    int n; fin >> n;
    queue<pair<int64_t, int>> q[2] = {};

    int node = 0;
    vector<int64_t> cost(2 * n);
    vector<pair<int, int>> tree(2 * n);

    for (int i = 0; i < n; i++) {
        int x; fin >> x;
        q[0].emplace(x, ++node);
    }

    int64_t total = 0;
    for (int i = 1; i < n; i++) {
        int64_t val = 0;
        int edges[2] = {};

        for (int j = 0; j < 2; j++) {
            int64_t vMin = 1e18; int qMin = -1;
            if (!q[0].empty() && q[0].front().first < vMin) vMin = q[qMin = 0].front().first;
            if (!q[1].empty() && q[1].front().first < vMin) vMin = q[qMin = 1].front().first;

            val += vMin;
            edges[j] = q[qMin].front().second;
            q[qMin].pop();
        }

        total += val;
        q[1].emplace(val, ++node);
        tree[node] = make_pair(edges[0], edges[1]);
    }

    fout << total << '\n';
    vector<pair<int, int64_t>> sol(2 * n);

    dfs(node, 0, 0, tree, sol);
    for (int i = 1; i <= n; i++)
        fout << sol[i].first << ' ' << sol[i].second << '\n';

    fout.close();
    return 0;
}