Cod sursa(job #2787990)

Utilizator cristi_macoveiMacovei Cristian cristi_macovei Data 24 octombrie 2021 16:22:15
Problema Coduri Huffman Scor 65
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.13 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;

class Heap {
private:
  std::queue<std::pair<int, int64_t>> a;
  std::queue<std::pair<int, int64_t>> b;

public:
  Heap() = default;

  void emplace(int first, int64_t second, bool toA = false) {
    if (toA)
      a.emplace(first, second);
    else
      b.emplace(first, second);
  }

  std::pair<int, int64_t> top() {
    if (a.empty())
      return b.front();

    if (b.empty())
      return a.front();

    if (a.front() < b.front())
      return a.front();

    return b.front();
  }

  void pop() {
    if (a.empty())
      b.pop();

    else if (b.empty())
      a.pop();

    else if (a.front() < b.front())
      a.pop();

    else 
      b.pop();
  }

  size_t size() {
    return a.size() + b.size();
  }
};

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

Heap heap;

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

void dfs(int node, int 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) };
  
  int cnt = 0;

  for (int 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, true);
    freq[i] = a;
  }

  int 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;
}