Cod sursa(job #1322425)

Utilizator deresurobertoFMI - Deresu Roberto deresuroberto Data 20 ianuarie 2015 00:46:15
Problema Coduri Huffman Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.97 kb
//Deresu Roberto - FMI
//Re :)
#include<fstream>
#include<queue>
#define nx 2000007
using namespace std;
int n;
long long sum;
char sir[10];
queue<pair<long long, int> >q1, q2;

struct st
{
  long long value;
  int left;
  int right;
}a[nx];

struct str
{
    int len;
    long long cod;
}b[nx/2];

ifstream fin("huffman.in");
ofstream fout("huffman.out");

void Minim(long long &nr,  int &pos)
{
    pair<long long, int> a;

    if(q1.empty())
    {
        a = q2.front();
        q2.pop();
    }
    else
    if(q2.empty())
    {
        a = q1.front();
        q1.pop();
    }
    else
    if(q1.front().first < q2.front().first)
    {
        a = q1.front();
        q1.pop();
    }
    else
    {
        a = q2.front();
        q2.pop();
    }

    nr = a.first;
    pos = a.second;
}

void Dfs(int pos, long long cod, int len)
{
    if(a[pos].left)
        Dfs(a[pos].left, cod<<1, len+1);
    if(a[pos].right)
        Dfs(a[pos].right, (cod<<1)+1, len+1);

    if(a[pos].left == 0 && a[pos].right == 0)
    {
        n++;
        b[pos].cod = cod;
        b[pos].len = len;
    }
    else sum += a[pos].value;
}

void Parse(int i)
{
    int j = 0;
    long long nr = 0;

    fin>>sir;

    while(sir[j])
    {
        nr = nr*10+sir[j]-'0';
        j++;
    }

    a[i].value = nr;
}


int main()
{
    fin>>n;

    for(int i = 1; i <= n; i++)
    {
        Parse(i);
        q1.push(make_pair(a[i].value, i));
    }

    while(q1.size()+q2.size() != 1)
    {
        long long nr1, nr2;
        int pos1, pos2;

        Minim(nr1, pos1);
        Minim(nr2, pos2);

        n++;
        a[n].value = nr1+nr2;
        q2.push(make_pair(a[n].value, n));
        a[n].left = pos1;
        a[n].right = pos2;
    }

    n = 0;
    Dfs(q2.front().second, 0, 0);

    fout << sum << '\n';

    for(int i = 1; i <= n; i++)
        fout << b[i].len << " " << b[i].cod << '\n';

    return 0;
}