Cod sursa(job #1949830)

Utilizator Train1Train1 Train1 Data 2 aprilie 2017 14:18:40
Problema Coduri Huffman Scor 65
Compilator cpp Status done
Runda Arhiva educationala Marime 1.3 kb
#include <iostream>
#include <fstream>
#include <queue>
using namespace std;
ifstream fin("huffman.in");
ofstream fout("huffman.out");
int n, v1[1000002];
long long v2[1000002];
struct nod {
    int val;
    long long length;
    nod *left, *right;
};
struct comp {
    bool operator() (nod *a, nod *b){
        return a->length > b->length;
    }
};
priority_queue <nod*, vector<nod*>, comp> pq;
void df(nod *R, int l, long long s) {
    if(R->val != 0) {
        v1[R->val] = l;
        v2[R->val] = s;
    } else {
        l++;
        df(R->left, l, s * 2);
        df(R->right, l, s * 2 + 1);
    }
}
int main()
{
    fin>>n;
    for(int i = 1; i <= n; i++) {
        nod *x = new nod;
        fin>>x->length;
        x->val = i;
        pq.push(x);
    }
    long long s = 0;
    while(pq.size() > 1) {
        nod *x = pq.top();
        pq.pop();
        nod *y = pq.top();
        pq.pop();

        long long k = x->length + y->length;
        nod *t = new nod;
        t->left = x;
        t->right = y;
        t->length = k;
        t->val = 0;
        s += k;
        pq.push(t);
    }
    fout<<s<<'\n';
    df(pq.top(), 0, 0);
    for(int i = 1; i <= n; i++) {
        fout<<v1[i]<<' '<<v2[i]<<'\n';
    }
    fin.close();
    fout.close();
    return 0;
}