Cod sursa(job #2845450)

Utilizator Tudor06MusatTudor Tudor06 Data 7 februarie 2022 20:55:50
Problema Coduri Huffman Scor 65
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <bits/stdc++.h>

using namespace std;


priority_queue <pair<int, int>> pq;

const int NMAX = 1e6;

int father[2 * NMAX + 1];
int value[2 * NMAX + 1];
int v[NMAX + 1];

int main() {
    ifstream fin( "huffman.in" );
    ofstream fout( "huffman.out" );
    int n, i, j, a;
    fin >> n;
    for ( i = 0; i < n; i ++ ) {
        fin >> v[i];
        pq.push( { -v[i], i } );
    }
    j = n;
    while ( pq.size() > 1 ) {
        pair<int, int> x1 = pq.top();
        pq.pop();
        pair<int, int> x2 = pq.top();
        pq.pop();
        value[x1.second] = 0;
        value[x2.second] = 1;
        father[x1.second] = father[x2.second] = j;
        pq.push( { x1.first + x2.first, j } );
        j ++;
    }
    long long lg = 0;
    vector <pair<int, int>> ans;
    j --;
    for ( i = 0; i < n; i ++ ) {
        int siz = 0, k = i;
        long long x = 0, p2 = 1;
        while ( k != j ) {
            siz ++;
            x += 1LL * value[k] * p2;
            p2 *= 2;
            k = father[k];
        }
        lg += siz * v[i];
        ans.push_back( { siz, x } );
    }
    fout << lg << '\n';
    for ( auto it : ans ) {
        fout << it.first << ' ' << it.second << '\n';
    }
    return 0;
}