Cod sursa(job #2787987)

Utilizator cristi_macoveiMacovei Cristian cristi_macovei Data 24 octombrie 2021 16:00:31
Problema Coduri Huffman Scor 65
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>

#define inout(f) std::ifstream in((f) + (std::string) ".in");std::ofstream out((f) + (std::string) ".out")
#define d(x) std::cout << x << std::endl
#define dm(msg, x) std::cout << msg << x << std::endl

const int NMAX = 1e6;

std::vector<int64_t> graph[1 + 2 * NMAX];

std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<std::pair<int, int>>> heap;

int64_t n;
std::pair<int64_t, int64_t> ans[1 + NMAX];
int64_t freq[1 + NMAX];

void dfs(int64_t node, int64_t depth, int64_t repr) {
  // std::printf("node %d, depth %d, repr %d\n", node, depth, repr);
  if (node <= n)
    ans[node] = { depth, repr - (1 << depth) };
  
  int64_t cnt = 0;

  for (int64_t i : graph[node]) {
    dfs(i, depth + 1, 2 * repr + cnt);
    cnt++;
  }
}

int main() {
  inout("huffman");

  in >> n;

  for (int i = 1; i <= n; ++i) {
    int a;
    in >> a;

    heap.emplace(a, i);
    freq[i] = a;
  }

  int64_t id = n;
  while (heap.size() > 1) {
    auto i = heap.top();
    heap.pop();

    auto j = heap.top();
    heap.pop();

    heap.emplace(i.first + j.first, ++id);

    graph[id].push_back(i.second);
    graph[id].push_back(j.second);
  }

  dfs(id, 0, 1);

  int64_t len = 0;
  for (int i = 1; i <= n; ++i) 
    len += ans[i].first * freq[i];
  out << len << '\n';

  for (int i = 1; i <= n; ++i) 
    out << ans[i].first << ' ' << ans[i].second << '\n';
  

  return 0;
}