Cod sursa(job #1958731)

Utilizator razvandRazvan Dumitru razvand Data 8 aprilie 2017 18:14:33
Problema Coduri Huffman Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include <iostream>
#include <queue>
#include <fstream>

using namespace std;

pair<int, int> kids[1000003];
int cod[1000003];
int ap[1000003];
int n;
int freq[1000003];

void rec(int nod, int crr, int am) {

    if(nod > n) {
        //cout << nod << " " << kids[nod].first << " " << kids[nod].second << " " << crr << " " << am << " " << crr + (1<<am) << '\n';
        rec(kids[nod].first, crr*2, am+1);
        rec(kids[nod].second, crr*2+1, am+1);
    } else {
        freq[nod] = am;
        cod[nod] = crr;
    }

}

int main() {

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

    in >> n;
    priority_queue<pair<int, int>> Q;
    int x;

    for(int i = 1; i <= n; i++) {
        in >> x;
        Q.push({-x, i});
        ap[i] = x;
    }

    int tim = n;
    int newC = 0;

    while(Q.size() != 1) {
        newC = 0;
        kids[++tim].first = Q.top().second;
        newC += Q.top().first;
        Q.pop();
        kids[tim].second = Q.top().second;
        newC += Q.top().first;
        Q.pop();
        Q.push({newC, tim});
    }

    int fin = Q.top().second;
    int tot = 0;

    rec(fin, 0, 0);

    for(int i = 1; i <= n; i++) {
        tot += freq[i]*ap[i];
    }

    out << tot << '\n';

    for(int i = 1; i <= n; i++) {
        out << freq[i] << " " << cod[i] << '\n';
    }


    return 0;
}