Cod sursa(job #1534676)

Utilizator dutzulBodnariuc Dan Alexandru dutzul Data 23 noiembrie 2015 21:19:37
Problema Coduri Huffman Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.77 kb
#include <bits/stdc++.h>

using namespace std;

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

#define ll long long
#define LE 1000666
#define newl cout<<'\n'
#define cout g

int result[LE],xx[LE];

class Node
{
public:

    int info;
    ll how_many;
    Node* left;
    Node* right;

    Node(int info,int how_many)
    {
        this->info=info;
        this->how_many=how_many;
        this->left=NULL;
        this->right=NULL;
    }
};

struct comp
{
    bool operator()(Node* i1,Node* i2)
    {
        return i1->how_many>i2->how_many;
    }
};


void dfs(Node* nod,int value)
{
    if (nod->info!=0) result[nod->info]=value;
    if (nod->left!=NULL) dfs(nod->left,value*2);
    if (nod->right!=NULL) dfs(nod->right,value*2+1);
}

priority_queue < Node*, vector<Node*> ,comp> que;

int bit_size(int val)
{
    if (val) return 1+bit_size(val/2);
    return 0;
}

int main()
{
    int n,i,sz=0;
    f>>n;

    if (n==1)
    {
        g<<1<<'\n';
        g<<1<<" "<<1<<'\n';
        return 0;
    }

    for(i=1; i<=n; ++i)
    {
        f>>xx[i];
        Node* aux=new Node(i,xx[i]);
        que.push(aux);
        ++sz;
    }

    while (sz>=2)
    {
        Node* v1= que.top();
        que.pop();
        Node* v2= que.top();
        que.pop();

        Node* aux=new Node(0,v1->how_many+v2->how_many);


        aux->left=v1;
        aux->right=v2;

        if (v1->how_many>v2->how_many) swap(aux->left,aux->right);

        que.push(aux);
        --sz;
    }


    dfs(que.top(),0);

    ll sum=0;

    for(i=1; i<=n; ++i)
    {
      //cout<<xx[i]<<" "<<bit_size(result[i])<<" " <<result[i]<<" "<<'\n';
      sum+=((ll)bit_size(result[i])*(ll)xx[i]);
   }

//newl;

    cout<<sum<<'\n';


    for(i=1; i<=n; ++i)
        cout<<max(1,bit_size(result[i]))<<" "<<result[i]<<'\n';


    return 0;
}