Cod sursa(job #2070800)

Utilizator Stefan_RaduStefan Radu Stefan_Radu Data 19 noiembrie 2017 22:19:29
Problema Coduri Huffman Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.38 kb
#include <cstdio>
#include <queue>
#include <cctype>
#include <vector>
   
using namespace std;

FILE *in, *out;
const int MAXBUFF = 4096;
char buff[MAXBUFF];
int index = MAXBUFF;

inline char next_char() {
  if (index == MAXBUFF) {
    fread(buff, 1, MAXBUFF, in);
    index = 0;
  }
  return buff[index ++];
}

inline int get_nr() {

  char chr = next_char();
  while (not isdigit(chr)) {
    chr = next_char();
  }

  int nr = 0;
  while (isdigit(chr)) {
    nr = nr * 10 + chr - '0';
    chr = next_char();
  }
  return nr;
}
   
struct node {
     
  node (long long val, int leaf) {
    for (auto &x : next_node) {
      x = NULL;
    }
    this -> val = val;
    this -> leaf_cnt = leaf;
  }
   
  int leaf_cnt;
  long long val;
  node* next_node[2];
};
   
inline void get_cur(queue < node* > &in_q, queue < node* > &sec_q, node* &cur_n) {
   
  if (in_q.size() and sec_q.size()) {
    if (in_q.front() -> val <= sec_q.front() -> val) {
      cur_n = in_q.front();
      in_q.pop();
    }
    else {
      cur_n = sec_q.front();
      sec_q.pop();
    }
  }
  else if (in_q.size()) {
    cur_n = in_q.front();
    in_q.pop();
  }
  else {
    cur_n = sec_q.front();
    sec_q.pop();
  }  
}
  
inline void Dfs(long long bin, int len, node* cur_node,
  vector < pair < int, long long > > &ans) {
   
  if (cur_node -> leaf_cnt) {
    ans[cur_node -> leaf_cnt] = {len, bin};
    return;
  }
   
  Dfs(bin << 1, len + 1, cur_node -> next_node[0], ans);
  Dfs(bin << 1 | 1, len + 1, cur_node -> next_node[1], ans);
}
   
int main(int argc, char const *argv[]) {
     
  in = fopen("huffman.in", "r");
  out = fopen("huffman.out", "w");
  
  int n = get_nr();
  node* cur = NULL;
  node* cur_left = NULL;
  node* cur_right = NULL;
  queue < node* > in_q;
  queue < node* > sec_q;
  vector < pair < int, long long > > ans(n + 1);
 
  for (int i = 1; i <= n; i ++) {
       
    int val = get_nr();
    in_q.push(new node(1ll * val, i));
  }
   
  long long sum = 0;
  while (in_q.size() + sec_q.size() > 1) {
   
    get_cur(in_q, sec_q, cur_left);
    get_cur(in_q, sec_q, cur_right);
   
    cur = new node(cur_left -> val + cur_right -> val, false);
    cur -> next_node[0] = cur_left;
    cur -> next_node[1] = cur_right;
    sec_q.push(cur);
    sum += cur -> val;
  }
   
  fprintf(out, "%lld\n", sum);
  Dfs(0, 0ll, cur, ans);
  for (int i = 1; i <= n; i ++) {
    fprintf(out, "%d %lld\n", ans[i].first, ans[i].second);
  }
}