Cod sursa(job #2615447)

Utilizator Mihai_PredaPreda Mihai Dragos Mihai_Preda Data 14 mai 2020 17:01:59
Problema Coduri Huffman Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.91 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

const int nMax = 1000005;
int lg;
long long cod;
long long total;
int n;
pair<int, long long> * rasp;

struct nod
{
    nod(long long val = -1)
    {
        this->val = val;
        child[0] = child[1] = -1;
    }
    void AddChildren(int x, int y)
    {
        child[0] = x, child[1] = y;
    }
    int child[2];
    long long val;
};

nod v[2*nMax];

int GetMin(queue<int> &a, queue<int> &b)
{
    int ret;
    if(a.empty() == false && (b.empty() == true || v[a.front()].val < v[b.front()].val))
    {
        ret = a.front();
        a.pop();
    }
    else
    {
        ret = b.front();
        b.pop();
    }
    return ret;
}

void DFS(int current)
{
    if(v[current].child[0] != -1)
    {
        for(int i = 0; i < 2; ++i)
        {
            lg++;
            cod = (cod << 1) + i;
            DFS(v[current].child[i]);
            lg--;
            cod >>= 1;
        }
    }
    if(current < n)
        rasp[current] = make_pair(lg, cod);
    else
        total += v[current].val;
}

int main()
{
    ifstream in("huffman.in");
    in >> n;
    queue<int> qElem, qSum;
    long long x;
    int t;
    for(int i = 0; i < n; ++i)
    {
        in >> x;
        v[i] = nod(x);
        qElem.push(i);
    }
    in.close();

    int a, b;
    int k = n;
    while(qElem.size() + qSum.size() > 1)
    {
        a = GetMin(qElem, qSum), b = GetMin(qElem, qSum);
        v[k] = nod(v[a].val + v[b].val);
        v[k].AddChildren(a, b);
        qSum.push(k);
        k++;
    }
    t = GetMin(qElem, qSum);
    rasp = new pair<int, long long>[n];
    DFS(t);

    ofstream out("huffman.out");
    out << total << "\n";
    for(int i = 0; i < n; ++i)
        out << rasp[i].first << " " << rasp[i].second << "\n";
    out.close();
    return 0;
}