Pagini recente » Cod sursa (job #755851) | Cod sursa (job #1786340) | Cod sursa (job #2157981) | Cod sursa (job #983000) | Cod sursa (job #2070654)
#include <cstdio>
#include <queue>
using namespace std;
struct node {
node (int val) {
this -> tata = NULL;
this -> val = val;
}
bool is_r = false;
long long val;
node* tata;
};
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 <= 62; i ++) {
pow_2[i] = (pow_2[i - 1] << 1ll);
}
}
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;
vector < node* > v(n + 1);
for (int i = 1; i <= n; i ++) {
int val;
scanf("%d ", &val);
v[i] = new node(1ll * val);
in_q.push(v[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);
cur_left -> tata = cur;
cur_right -> tata = cur;
cur_right -> is_r = true;
sec_q.push(cur);
sum += cur -> val;
}
printf("%lld\n", sum);
for (int i = 1; i <= n; i ++) {
cur = v[i];
int len = 0;
long long ans = 0;
while (cur -> tata) {
if (cur -> is_r) {
ans += pow_2[len];
}
len ++;
cur = cur -> tata;
}
printf("%d %lld\n", len, ans);
}
}