Cod sursa(job #2617981)

Utilizator andreitudorpAndrei Tudor Popescu andreitudorp Data 23 mai 2020 14:02:04
Problema Coduri Huffman Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <fstream>
#include <queue>
using namespace std;

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

typedef long long ll ;
#define MAXN 2000005

queue<int> before, after;

int n;
ll val[MAXN];
int st[MAXN], dr[MAXN];
pair<ll, ll> ans[MAXN];
ll sum;

void DFS(int nod, int depth, ll nr){

    if(!st[nod] && !dr[nod])
    {
        ans[nod].first = depth;
        ans[nod].second = nr;
        return;
    }

    sum += val[nod];

    DFS(st[nod], depth + 1, nr * 2);
    DFS(dr[nod], depth + 1, nr * 2 + 1);

}

void adauga_nod(int x, int y)
{
    val[++n] = val[x] + val[y];
    st[n] = x;
    dr[n] = y;
    after.push(n);
}

int minx() {
    int nr;
    if (!before.empty()) {

        if (!after.empty()) {

            if (val[before.front()] < val[after.front()])
            {
                nr = before.front();
                before.pop();
            }

            else
            {
                nr = after.front();
                after.pop();
            }
        }

        else
        {
            nr = before.front();
            before.pop();
        }
    }
    else
    {
        nr = after.front();
        after.pop();
    }
    return nr;
}

int main() {
    int m;
    cin >> n;
    m = n;

    int x, y;

    for(int i = 1; i <= n; ++i)
    {
        cin >> x;
        val[i] = x;
        before.push(i);
    }

    while(before.size() + after.size() > 1)
    {
        x = minx(), y = minx();
        adauga_nod(x, y);
    }

    DFS(n, 0, 0);

    cout << sum << "\n";

    for(int i = 1; i <= m; ++i)
        cout << ans[i].first << " " << ans[i].second << "\n";

    return 0;
}