Cod sursa(job #2615150)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 13 mai 2020 18:48:31
Problema Coduri Huffman Scor 70
Compilator cpp-32 Status done
Runda Arhiva educationala Marime 1.8 kb
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

ifstream cin("huffman.in");
ofstream cout("huffman.out");

const int NMAX = 1e6;

int N, K;

long long wei[2 * NMAX + 2];
queue < int > q[3];

int lenChar[NMAX + 2];
long long valChar[NMAX + 2];

pair <int, bool> g[2 * NMAX + 10][2];

void dfs(int node, int h, long long valTo)
{
    if(node <= N)
    {
        lenChar[node] = h;
        valChar[node] = valTo;
        return;
    }

    for(int i = 0; i < 2; i++)
    {
        pair <int, bool> it = g[node][i];
        dfs(it.first, h + 1, (valTo << 1) + it.second);
    }
}

int GetMin()
{
    if(q[1].empty())
    {
        int ind = q[2].front();
        q[2].pop();
        return ind;
    }

    if(q[2].empty())
    {
        int ind = q[1].front();
        q[1].pop();
        return ind;
    }

    if(wei[q[1].front()] < wei[q[2].front()])
    {
        int ind = q[1].front();
        q[1].pop();
        return ind;
    }

    int ind = q[2].front();
    q[2].pop();
    return ind;
}

int main()
{
    cin >> N;
    K = N;

    for(int i = 1; i <= N; i++)
    {
        cin >> wei[i];
        q[1].push(i);
    }

    if(N == 1)
    {
        cout << wei[1] << "\n1 0\n";
        return 0;
    }

    while(q[1].size() + q[2].size() > 1)
    {
        int f = GetMin();
        int s = GetMin();

        K++;
        g[K][0] = {f, 0};
        g[K][1] = {s, 1};

        wei[K] = wei[f] + wei[s];
        q[2].push(K);
    }

    dfs(K, 0, 0);

    long long totalSz = 0;
    for(int i = 1; i <= N; i++)
        totalSz = totalSz + 1LL * wei[i] * lenChar[i];

    cout << totalSz << '\n';
    for(int i = 1; i <= N; i++)
        cout << lenChar[i] << ' ' << valChar[i] << '\n';

    return 0;
}