Cod sursa(job #1556491)

Utilizator ThomasFMI Suditu Thomas Thomas Data 24 decembrie 2015 23:14:10
Problema Coduri Huffman Scor 65
Compilator cpp Status done
Runda Arhiva educationala Marime 1.82 kb
#include <fstream>
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;

#define NMax 1000005

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

struct arbore
{
    long long val;
    arbore *left, *right;

    arbore(long long x)
    {
        val = x;
        left = right = NULL;
    }

    arbore() {}
};

queue<arbore*> cd1, cd2;

arbore* extract_min()
{
    if(cd1.empty())
    {
        arbore *y = cd2.front();
        cd2.pop();
        return y;
    }
    if(cd2.empty())
    {
        arbore *x = cd1.front();
        cd1.pop();
        return x;
    }

    arbore *x = cd1.front(), *y = cd2.front();
    if(x->val < y->val)
    {
        cd1.pop();
        return x;
    }
    else
    {
        cd2.pop();
        return y;
    }
}

int n;
long long sum;
pair<int,pair<int,int>> v[NMax];
int nr;

void DFS(arbore* nod, long long mask, int depth)
{
    if(nod->left == NULL && nod->right == NULL)
    {
        v[++nr] = make_pair(nod->val, make_pair(depth, mask));
    }
    else
    {
        sum += nod->val;
        DFS(nod->left, (mask<<1), depth+1);
        DFS(nod->right, (mask<<1)|1, depth+1);
    }
}

int main()
{
    int i,x;
    f>>n;
    for(i=1;i<=n;++i)
    {
        f>>x;
        cd1.push(new arbore(x));
    }

    arbore* aux;
    while(cd1.size() + cd2.size() > 1)
    {
        aux = new arbore();
        aux->left = extract_min();
        aux->right = extract_min();
        aux->val = aux->left->val + aux->right->val;
        cd2.push(aux);
    }

    arbore *root = cd2.front();

    DFS(root, 0, 0);

    g<<sum<<"\n";

    sort(v+1,v+nr+1);
    for(i=1;i<=nr;++i)
    {
        g<<v[i].second.first<<" "<<v[i].second.second<<"\n";
    }

    f.close();
    g.close();
    return 0;
}