Cod sursa(job #2062427)

Utilizator Alex18maiAlex Enache Alex18mai Data 10 noiembrie 2017 13:03:43
Problema Coduri Huffman Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.82 kb
#include <fstream>
#include <queue>

using namespace std;

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

pair<int , int> node[2000100];
pair<int , long long> ans[1000100];

queue <pair<long long , int>> q;
queue <pair<long long , int>> Q;

void give_val(pair<long long , int> &a ){
    if (q.empty()){
        a.first = Q.front().first;
        a.second = Q.front().second;
        Q.pop();
    }
    else if (Q.empty()){
        a.first = q.front().first;
        a.second = q.front().second;
        q.pop();
    }
    else if (q.front().first < Q.front().first){
        a.first = q.front().first;
        a.second = q.front().second;
        q.pop();
    }
    else {
        a.first = Q.front().first;
        a.second = Q.front().second;
        Q.pop();
    }
}

void dfs(int nod , int lv , long long val){

    if (node[nod].first == 0){
        ans[nod].first = lv;
        ans[nod].second = val;
        return;
    }

    dfs(node[nod].first , lv + 1 , (val << 1LL));
    dfs(node[nod].second , lv + 1 , (val << 1LL) + 1LL);

}

int main() {

    ios::sync_with_stdio(false);
    cin.tie(NULL);

    int n;
    cin>>n;

    for (int i=1; i<=n; i++){
        long long nr;
        cin>>nr;
        q.push({nr , i});
    }

    long long cont = 0;
    int nod = n;

    while (true){

        if (Q.size() == 1 && q.empty()){
            break;
        }

        pair<long long , int> st , dr;

        give_val(st);
        give_val(dr);

        nod ++;
        cont += st.first + dr.first;
        //cout<<"ramific "<<st.second<<" "<<dr.second<<'\n';

        Q.push({st.first + dr.first , nod});
        node[nod].first = st.second;
        node[nod].second = dr.second;
    }

    cout<<cont<<'\n';

    dfs(nod , 0 , 0);

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

    return 0;
}