Cod sursa(job #1511002)

Utilizator sebinechitasebi nechita sebinechita Data 25 octombrie 2015 21:36:14
Problema Coduri Huffman Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.74 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <conio.h>
using namespace std;
ifstream fin("huffman.in");
ofstream fout("huffman.out");
#define MAX 1000100
struct nod{
long long val;
int ind;
nod *st, *dr;
};
queue<nod*> Q1, Q2;
nod* extrage()
{
    nod *r;
    if(Q1.size() == 0)
    {
        r = Q2.front();
        Q2.pop();
        return r;
    }
    if(Q2.size() == 0)
    {
        r = Q1.front();
        Q1.pop();
        return r;
    }
    if(Q2.front()->val < Q1.front()->val)
    {
        r = Q2.front();
        Q2.pop();
        return r;
    }
    r = Q1.front();
    Q1.pop();
    return r;
}

long long sol, b[MAX];
int a[MAX];

void df(nod *x, int lg, long long y)
{
 //   cout << x->val << " " << lg << ' ' << y << " " << x->st->val << " " << x->dr->val <<  "\n";
   // getch();
    if(x->ind)
    {
        sol += 1ll * lg * x->val;
        a[x->ind] = lg;
        b[x->ind] = y;
        return;
    }
    df(x->st, lg + 1, 2ll * y);
    df(x->dr, lg + 1, 2ll * y + 1);
}

int main()
{
    int n, i;
    fin >> n;
    for(i = 1 ; i <= n ; i++)
    {
        nod *x = new nod;
        fin >> x->val;
        x->ind = i;
        x->st = x->dr = 0;
        Q1.push(x);
    }
    for(i = 1 ; i < n ; i++)
    {
        nod *x = extrage();
        nod *y = extrage();
        nod *z = new nod;

        z->val = x->val + y->val;
        z->st = x;
        z->dr = y;
       // cout << z->val << " " << z->st->val << " " << z->dr->val << "\n";
        z->ind = 0;
        Q2.push(z);
    }
    nod *root = extrage();
    df(root, 0, 0);
    fout << sol << "\n";
    for(i = 1 ; i <= n ; i++)
    {
        fout << a[i] << " " << b[i] << "\n";
    }
}