Cod sursa(job #1905820)

Utilizator cella.florescuCella Florescu cella.florescu Data 6 martie 2017 11:03:52
Problema Coduri Huffman Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include <bits/stdc++.h>

using namespace std;

const int MAXN = 1e6;

long long v[2 * MAXN + 1], code[MAXN + 1];
int q1[MAXN + 1], q2[MAXN + 1], len[MAXN + 1], son[2][2 * MAXN + 1];
int b1, e1, b2, e2;

inline int get_min_q() {
  if (b1 > e1)
    return q2[b2++];
  if (b2 > e2)
    return q1[b1++];
  if (v[q1[b1]] < v[q2[b2]])
    return q1[b1++];
  return q2[b2++];
}

void dfs(int node, long long cod, int lev) {
  if (son[0][node]) {
    dfs(son[0][node], 2 * cod, lev + 1);
    dfs(son[1][node], 2 * cod + 1, lev + 1);
    return;
  }
  len[node] = lev;
  code[node] = cod;
}

int main()
{
    long long ans;
    int n, nodes, x, y;
    ifstream fin("huffman.in");
    fin >> n;
    nodes = 0;
    e1 = e2 = -1;
    for (int i = 0; i < n; ++i) {
      fin >> v[++nodes];
      q1[++e1] = nodes;
    }
    fin.close();
    while (e1 + e2 - b1 - b2 >= 0) {
      x = get_min_q();
      y = get_min_q();
      v[++nodes] = v[x] + v[y];
      q2[++e2] = nodes;
      son[0][nodes] = x; son[1][nodes] = y;
    }
    dfs(nodes, 0, 0);
    ans = 0LL;
    for (int i = 1; i <= n; ++i)
      ans += 1LL * len[i] * v[i];
    ofstream fout("huffman.out");
    fout << ans << '\n';
    for (int i = 1; i <= n; ++i)
      fout << len[i] << " " << code[i] << '\n';
    fout.close();
    return 0;
}