Cod sursa(job #2622964)

Utilizator tudor331Fulga Tudor Mihai tudor331 Data 2 iunie 2020 12:46:20
Problema Coduri Huffman Scor 0
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <bits/stdc++.h>

using namespace std;

const int N = 2e6 + 1;

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

int n, nr, st[N], dr[N], nivel[N];
long long val[N], cod[N];
queue <int> q1, q2;

int selectie()
{
    int minim;
    if (q1.empty())
    {
        minim = q2.front();
        q2.pop();
        return minim;
    }
    if (q2.empty())
    {
        minim = q1.front();
        q1.pop();
        return minim;
    }
    if (val[q1.front()] <= val[q2.front()])
    {
        minim = q1.front();
        q1.pop();
    }
    else
    {
        minim = q2.front();
        q2.pop();
    }
    return minim;
}

void adauga(int x, int y)
{
    val[++nr] = val[x]+ val[y];
    st[nr] = x;
    dr[nr] = y;
    q2.push(nr);
}

long long rsd(int x)
{
    long long suma = 0;
    if (st[x] != 0)
    {
        cod[st[x]] = cod[x] * 2;
        nivel[st[x]] = 1 + nivel[x];
        cod[dr[x]] = cod[x] * 2 + 1;
        nivel[dr[x]] = 1 + nivel[x];
        suma += val[x] + rsd(st[x]) + rsd(dr[x]);
    }
    return suma;
}

int main()
{
    in >> n;
    for(int i = 1; i <= n; i++)
    {
        in >> val[i];
        q1.push(i);
    }
    in.close();
    nr = n;
    while(q1.size() + q2.size() > 1)
    {
        int x = selectie();
        int y = selectie();
        adauga(x,y);
    }
    out << rsd(nr) << "\n";
    for(int i = 1; i <= n; i++)
    {
        out << nivel[1] << " " << cod[i] << "\n";
    }
    out.close();
    return 0;
}