Cod sursa(job #2428805)

Utilizator AlexNeaguAlexandru AlexNeagu Data 6 iunie 2019 15:53:35
Problema Coduri Huffman Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include<bits/stdc++.h>
typedef long long ll;
#define nmax 1000005
#define inf 0x3f3f3f3f3f3f3f3f

using namespace std;

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

ll  b[nmax], mn, sol = 0;
long n, i, j, k, p , l[2], r[2], q[2][nmax], lg[nmax];
struct nod
{
  ll v;
  long f[2];
} nod[2 * nmax + 1];

void df(long pos, ll code, long lvl)
{
     //cout << nod[pos].v << " " << nod[pos].f[0] << " " << nod[pos].f[1] << "\n";
     if (nod[pos].f[0])
     {
       df(nod[pos].f[0], code*2, lvl + 1);
       df(nod[pos].f[1], code*2+1, lvl + 1);
       return;
     }
     lg[pos] = lvl;
     b[pos] = code;
     //cout << lg[pos] << " " << b[pos] << " " << pos << "\n";
}
void solve()
{
   k = n;
   l[0] =  l[1] = 1;
   r[0] = n;
   while (l[0] + l[1] <= r[0] + r[1])
   {
     ++k;
     for (j = 0; j < 2; j++)
     {
       p = 0;
       mn = inf;
       for (i = 0; i < 2; i++)
       {
         if (nod[q[i][l[i]]].v < mn && l[i] <= r[i])
         {
           p = i;
           mn = nod[q[i][l[i]]].v;
         }
       }
       nod[k].f[j] = q[p][l[p]];
       nod[k].v += nod[q[p][l[p]]].v;
       l[p]++;
     }
     sol += nod[k].v;
     q[1][++r[1]] = k;
   }
   df(k,0,0);
}

int main()
{
  ios_base::sync_with_stdio(0); cin.tie(0);

  fin >> n;

  for (i = 1; i <= n; i++)
  {
    fin >> nod[i].v;
    q[0][i] = i;
  }
  solve();
  fout << sol << "\n";
  for (i = 1; i <= n; i++)
  fout << lg[i] << " " << b[i] << "\n";
  return 0;
}