Cod sursa(job #2725614)

Utilizator Alex_tz307Lorintz Alexandru Alex_tz307 Data 19 martie 2021 12:39:31
Problema Coduri Huffman Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.49 kb
#include <bits/stdc++.h>

using namespace std;
using int64 = long long;

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

const int NMAX = 1e6 + 6;
int N, lg[NMAX], idx, st[NMAX << 1], dr[NMAX << 1];
int64 sol[NMAX], wt[NMAX << 1], ans;
queue<int> Q1, Q2;

void read_input() {
  fin >> N;
  for (int i = 1; i <= N; ++i) {
    fin >> wt[i];
    Q1.emplace(i);
  }
}

int take_best() {
  int ans;
  if (Q2.empty()) {
    ans = Q1.front();
    Q1.pop();
  } else {
    if (Q1.empty()) {
      ans = Q2.front();
      Q2.pop();
    } else {
      if (wt[Q1.front()] < wt[Q2.front()]) {
        ans = Q1.front();
        Q1.pop();
      } else {
        ans = Q2.front();
        Q2.pop();
      }
    }
  }
  return ans;
}

void dfs(int u, int64 mask, int depth) {
  if (u <= N) {
    sol[u] = mask;
    lg[u] = depth;
    ans += wt[u] * depth;
    return;
  }
  if (st[u])
    dfs(st[u], mask << 1LL, depth + 1);
  if (dr[u])
    dfs(dr[u], mask << 1LL | 1LL, depth + 1);
}

void solve() {
  idx = N;
  while (Q1.size() + Q2.size() > 1) {
    int lSon = take_best(), rSon = take_best();
    wt[++idx] = wt[lSon] + wt[rSon];
    st[idx] = lSon, dr[idx] = rSon;
    Q2.emplace(idx);
  }
  dfs(Q2.front(), 0, 0);
  fout << ans << '\n';
  for (int i = 1; i <= N; ++i)
    fout << lg[i] << ' ' << sol[i] << '\n';
}

void close_files() {
  fin.close();
  fout.close();
}

int main() {
  read_input();
  solve();
  close_files();
  return 0;
}