Cod sursa(job #2062368)

Utilizator Alex18maiAlex Enache Alex18mai Data 10 noiembrie 2017 12:02:02
Problema Coduri Huffman Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.97 kb
#include <fstream>
#include <queue>
#include <cmath>

using namespace std;

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

class cmp{
public:
    bool operator() (pair<long long , long long> a , pair<long long , long long> b){
        return a.first > b.first;
    }
};

long long nr[1000100];
pair<long long , long long> node[20000100];
pair<long long , long long> ans[1000100];

priority_queue <pair<long long , long long> , vector<pair<long long , long long>> , cmp> Q;
queue <pair<long long ,pair<long long, long long>>> q;

int main() {

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

    long long n;
    cin>>n;

    for (long long i=1; i<=n; i++){
        cin>>nr[i];
        Q.push({nr[i] , i});
    }

    long long cont = 0;
    long long nod = n;

    while (Q.size() > 1){
        pair<long long , long long> st , dr;
        st.first = Q.top().first;
        st.second = Q.top().second;
        Q.pop();
        dr.first = Q.top().first;
        dr.second = Q.top().second;
        Q.pop();

        nod++;

        node[nod].first = st.second;
        node[nod].second = dr.second;

        Q.push({st.first + dr.first , nod});
        cont += st.first + dr.first;
    }

    cout<<cont<<'\n';

    q.push({Q.top().second , {0 , 0}});

    while (!q.empty()){

        pair<long long ,pair<long long , long long>> now;
        now.first = q.front().first;
        now.second.first = q.front().second.first;
        now.second.second = q.front().second.second;
        q.pop();

        if (node[now.first].first == 0){
            ans[now.first].first = now.second.first;
            ans[now.first].second = now.second.second;
            continue;
        }

        q.push({node[now.first].first , {now.second.first + 1LL , now.second.second << 1LL}});
        q.push({node[now.first].second , {now.second.first + 1LL , (now.second.second << 1LL) + 1LL}});

    }

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

    return 0;
}