Pagini recente » Cod sursa (job #1706207) | Cod sursa (job #3186500) | Cod sursa (job #2682081) | Cod sursa (job #2898216) | Cod sursa (job #2070311)
#include <cstdio>
#include <queue>
using namespace std;
struct node {
node (int val, bool is) {
for (auto &x : next_node) {
x = NULL;
}
this -> val = val;
this -> is_in = is;
}
long long val;
bool is_in;
node* next_node[2];
};
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();
}
}
void Init(long long pow_2[]) {
pow_2[0] = 1ll;
for (int i = 1; i <= 63; i ++) {
pow_2[i] = (pow_2[i - 1] << 1ll);
}
}
void Print(long long cur_code, int cur_pow, long long pow_2[], node* cur_node) {
if (cur_node -> is_in) {
printf("%d %lld\n", cur_pow, cur_code);
return;
}
if (cur_node -> next_node[0]) {
Print(cur_code, cur_pow + 1, pow_2, cur_node -> next_node[0]);
}
if (cur_node -> next_node[1]) {
Print(cur_code + pow_2[cur_pow], cur_pow + 1, pow_2, cur_node -> next_node[1]);
}
}
int main(int argc, char const *argv[]) {
freopen("huffman.in", "r", stdin);
freopen("huffman.out", "w", stdout);
long long pow_2[100];
Init(pow_2);
int n;
scanf("%d", &n);
node* cur = NULL;
node* cur_left = NULL;
node* cur_right = NULL;
queue < node* > in_q;
queue < node* > sec_q;
for (int i = 1; i <= n; i ++) {
int val;
scanf("%d ", &val);
in_q.push(new node(1ll * val, true));
}
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, 0);
cur -> next_node[0] = cur_left;
cur -> next_node[1] = cur_right;
sec_q.push(cur);
sum += cur -> val;
}
printf("%lld\n", sum);
Print(0, 0, pow_2, cur);
}