Cod sursa(job #2887238)

Utilizator matei123Biciusca Matei matei123 Data 9 aprilie 2022 01:26:12
Problema Coduri Huffman Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("huffman.in");
ofstream g("huffman.out");

queue<int> before, after;
int n;
#define MAXN 2000005

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

void DFS(int nod, long long depth, long long 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;
    f >> n;
    m = n;
    int x, y;
    for(int i = 1; i <= n; ++i) {
        f >> 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);
    g << sum << "\n";
    for(int i = 1; i <= m; ++i)
        g << ans[i].first << " " << ans[i].second << "\n";
    return 0;
}