Cod sursa(job #2738149)

Utilizator StanSiBranBranSiStan StanSiBran Data 5 aprilie 2021 15:00:07
Problema Coduri Huffman Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <bits/stdc++.h>
#define ll long long
#define ld long double
 
using namespace std;
 
const ll MOD = 1e9 + 7;
const ll INF = 1e9;
const int N = 1e6 + 1;
 
ifstream fin ("huffman.in");
ofstream fout ("huffman.out");
 
int n, x, nod;
queue<pair<long long, int> >q1, q2;
int son1[2 * N], son2[2 * N];
ll ans;
ll sol[N];
int len[N];
 
void dfs (int nr, ll val, int depth = 0) {
  if (nr <= n) {
    sol[nr] = val;
    len[nr] = depth;
    return;
  }
  dfs(son1[nr], val * 2, depth + 1);
  dfs(son2[nr], val * 2 + 1, depth + 1);
}
 
int main()
{
  //ios_base::sync_with_stdio(false);
  //fin.tie(0); fout.tie(0);
  fin >> n;
  for (int i = 1; i <= n; i++) {
    fin >> x;
    q1.push({x, i});
  }
  nod = n;
  while (q1.size() + q2.size() > 1) {
    vector<pair<long long, int> >lol;
    while (lol.size() < 2) {
      if (q2.empty()) {
        lol.push_back(q1.front());
        q1.pop();
      }
      else if (q1.empty()) {
        lol.push_back(q2.front());
        q2.pop();
      }
      else if (q1.front() < q2.front()) {
        lol.push_back(q1.front());
        q1.pop();
      }
      else {
        lol.push_back(q2.front());
        q2.pop();
      }
    }
    nod++;
    son1[nod] = lol[0].second;
    son2[nod] = lol[1].second;
    ans += lol[0].first + lol[1].first;
    q2.push({lol[0].first + lol[1].first, nod});
  }
  fout << ans << "\n"; 
  dfs(nod, 0);
  for (int i = 1; i <= n; i++)
    fout << len[i] << " " << sol[i] << "\n";
  return 0;
}