Cod sursa(job #1905827)

Utilizator cella.florescuCella Florescu cella.florescu Data 6 martie 2017 11:09:27
Problema Coduri Huffman Scor 100
Compilator cpp Status done
Runda cerculdeinfo-lectia15-ev_p_s_q_dq_dp Marime 1.39 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()
{
    FILE *fin, *fout;
    long long ans;
    int n, nodes, x, y;
    fin = fopen("huffman.in", "r");
    fscanf(fin, "%d", &n);
    nodes = 0;
    e1 = e2 = -1;
    for (int i = 0; i < n; ++i) {
      fscanf(fin, "%d", v + nodes + 1);
      q1[++e1] = ++nodes;
    }
    fclose(fin);
    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];
    fout = fopen("huffman.out", "w");
    fprintf(fout, "%lld\n", ans);
    for (int i = 1; i <= n; ++i)
      fprintf(fout, "%d %lld\n", len[i], code[i]);
    fclose(fout);
    return 0;
}