Cod sursa(job #2617952)

Utilizator stefanpiturStefan Alexandru Pitur stefanpitur Data 23 mai 2020 13:19:18
Problema Coduri Huffman Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#include <iostream>
#include <fstream>
#include <queue>
using namespace std;

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

const int N = 1000000;

queue <int> q1, q2;

long long code[2*N + 1];
int st[2*N + 1], dr[2*N + 1];
int n, cn;

long long sum;

struct {
    int depth;
    long long val;
} output[N + 1];

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

int get_min(){
    int ans;
    if(!q1.empty()){
        if(!q2.empty()){
            if(code[q1.front()] < code[q2.front()]){
                ans = q1.front();
                q1.pop();
            }
            else{
                ans = q2.front();
                q2.pop();
            }
        }
        else{
            ans = q1.front();
            q1.pop();
        }
    }
    else{
        ans = q2.front();
        q2.pop();
    }
    return ans;
}


void dfs(int node, int depth, long long val){
    if(st[node] == 0 && dr[node] == 0){
        output[node].depth = depth, output[node].val = val;
        return;
    }
    sum += code[node];
    dfs(st[node], depth + 1, val * 2);
    dfs(dr[node], depth + 1, val * 2 + 1);
}

int main()
{
    int i,e1,e2;
    fin >> n;
    cn = n;
    for(i=1; i<=n; i++){
        fin >> code[i];
        q1.push(i);
    }
    while((int)q1.size() + (int)q2.size() > 1){
        e1 = get_min();
        e2 = get_min();
        adauga_nod(e1, e2);
    }
    dfs(n, 0, 0);
    fout << sum << "\n";
    for(i=1; i<=cn; i++)
        fout << output[i].depth << " " << output[i].val << "\n";
    return 0;
}