Cod sursa(job #2281390)

Utilizator Iulia25Hosu Iulia Iulia25 Data 12 noiembrie 2018 10:26:04
Problema Coduri Huffman Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <fstream>
#include <queue>

using namespace std;

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

int nr[2000001], n, a, st[2000001], dr[2000001], total;
int nod[1000001], nrnod, x1, x2;
int p[1000001], g[1000001];

auto cmp = [](int x, int y)  {
  return (nr[x] > nr[y]);
};

priority_queue <int, vector<int>, decltype(cmp)> pq(cmp);

void check(int node, int grad, int prod)  {
  if (!st[node])  {
    total += nr[node] * grad;
    g[node] = grad;
    p[node] = prod;
  }
  else  {
    check(st[node], grad + 1, prod * 2);
    check(dr[node], grad + 1, prod * 2 + 1);
  }
}

int main()  {
  fin >> n;
  for (int i = 1; i <= n; ++i)  {
    fin >> a;
    nod[i] = ++nrnod;
    nr[nod[i]] = a;
    pq.push(nod[i]);
  }
  while (!pq.empty())  {
    x1 = pq.top();
    pq.pop();
//    fout << x1 << ' ' << nr[x1] << '\n';
    if (!pq.empty())  {
      x2 = pq.top();
      pq.pop();
      nr[++nrnod] = nr[x1] + nr[x2];
      pq.push(nrnod);
      st[nrnod] = x1;
      dr[nrnod] = x2;
    }
  }
  check(nrnod, 0, 0);
  fout << total << '\n';
  for (int i = 1; i <= n; ++i)
    fout << g[i] << ' ' << p[i] << '\n';
}