Cod sursa(job #2219401)

Utilizator VladTiberiuMihailescu Vlad Tiberiu VladTiberiu Data 8 iulie 2018 18:48:00
Problema Coduri Huffman Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.07 kb
#include <bits/stdc++.h>

using namespace std;

#define ll long long
#define DIM 10000

ll poz = 0;
char buffer[DIM];

void cit(ll &n){
    n = 0;
    while(buffer[poz] < '0' || buffer[poz] > '9'){
        if(++poz == DIM){
            fread(buffer,sizeof(char),DIM,stdin);
            poz = 0;
        }
    }
    while(buffer[poz] >= '0' && buffer[poz] <= '9'){
        n = n * 10 + buffer[poz] - '0';
        if(++poz == DIM){
            fread(buffer,sizeof(char),DIM,stdin);
            poz = 0;
        }
    }
}

const ll NMax = 1000003;

struct Node{
    ll value;
    Node *left,*right;
};

multiset<pair<ll, Node*> > heap;
Node *root;
ll n,x,ans;
ll a[NMax],l[NMax],freq[NMax];

void GetKeyValues(ll curr_nr, ll iteration, Node* node){
    if(node->value == -1){
        GetKeyValues((curr_nr << 1), iteration + 1, node->left);
        GetKeyValues((curr_nr << 1) + 1, iteration + 1, node->right);
        return;
    }
    l[node->value] = iteration;
    a[node->value] = curr_nr;
    ans += l[node->value] * freq[node->value];
    return;
}
int main(){
    freopen("huffman.in","r",stdin);
    freopen("huffman.out","w",stdout);
    cit(n);
    for(ll i = 1; i <= n; ++i){
        cit(x);
        Node *aux = new Node;
        aux->value = i;
        freq[i] = x;
        aux->left = aux->right = nullptr;
        heap.insert({x,aux});
    }
    while(!heap.empty()){
        pair<ll, Node*> first_pair = *(heap.begin());
        Node *first = first_pair.second;
        heap.erase(heap.begin());
        pair<ll, Node*> second_pair = *(heap.begin());
        Node *second = second_pair.second;
        heap.erase(heap.begin());
        Node *aux = new Node;
        aux->value = -1;
        aux->left = first;
        aux->right = second;
        if(heap.empty()){
            root = aux;
            break;
        }
        heap.insert({first_pair.first + second_pair.first, aux});
    }
    GetKeyValues(0,0,root);
    printf("%lld\n",ans);
    for(ll i = 1; i <= n; ++i){
        printf("%lld %d\n",l[i],a[i]);
    }
}