Cod sursa(job #2623166)

Utilizator PetyAlexandru Peticaru Pety Data 2 iunie 2020 18:12:28
Problema Coduri Huffman Scor 85
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <bits/stdc++.h>

using namespace std;

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

int q[2000002], n, nr, st[2000002], dr[2000002], len[2000002];
int a, b;
long long v[2000002], ans[2000002];

void Union (int x, int y) {
  nr++;
  v[nr] = v[x] + v[y];
  st[nr] = x;
  dr[nr] = y;
  q[++b] = nr;
}

void calc (int x) {
  if (st[x] != 0) {
    ans[st[x]] = ans[x] * 2;
    len[st[x]] = len[x] + 1;
    calc(st[x]);
  }
  if (dr[x] != 0) {
    ans[dr[x]] = ans[x] * 2 + 1;
    len[dr[x]] = len[x] + 1;
    calc(dr[x]);
  }
}

int main()
{
  fin >> n;
  for (int i = 1; i <= n; i++)
    fin >> v[i];
  b = -1;
  nr = n;
  Union(1, 2);
  int i = 3;
  while (i <= n || a < b) {
    if (i <= n && v[i] <= v[q[a]]) {
      if (i < n && v[i + 1] <= v[q[a]]) {
        Union(i, i + 1);
        i += 2;
      }
      else {
        Union(i, q[a]);
        i++; a++;
      }
    }
    else if (i <= n && (v[i] <= v[q[a + 1]])){
      Union(i, q[a]);
      i++; a++;
    }
    else {
      Union(q[a], q[a + 1]);
      a += 2;
    }
  }
  calc(nr);
  long long sum = 0;
  for (int i = n + 1; i <= nr; i++)
    sum += v[i];
  fout << sum << "\n";
  for (int i = 1; i <= n; i++)
    fout << len[i] << " " << ans[i] << "\n";
  return 0;
}