Cod sursa(job #3127423)

Utilizator dandragosDan Dragos dandragos Data 7 mai 2023 15:24:08
Problema Coduri Huffman Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.14 kb
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

struct node {
int weight, left_child, right_child, level;
long long code;
};

int n;
vector<node> heap;

bool compare(node a, node b) {
return a.weight > b.weight;
}

void build_tree(node& n, int level, long long code) {
n.level = level;
n.code = code;
if (n.left_child != -1) {
build_tree(heap[n.left_child], level + 1, code << 1);
build_tree(heap[n.right_child], level + 1, (code << 1) | 1);
}
}

int main() {
cin >> n;
heap.resize(n);
for (int i = 0; i < n; i++) {
cin >> heap[i].weight;
heap[i].left_child = heap[i].right_child = -1;
}
sort(heap.begin(), heap.end(), compare);
for (int i = n; i < 2 * n - 1; i++) {
node n;
n.weight = heap.back().weight;
n.left_child = heap.size() - 1;
heap.pop_back();
n.right_child = heap.size() - 1;
heap.pop_back();
heap.push_back(n);
}
build_tree(heap.back(), 0, 0);
long long total_weight = 0;
for (int i = 0; i < n; i++) {
total_weight += heap[i].weight;
}
cout << total_weight << endl;
for (int i = 0; i < n; i++) {
cout << heap[i].level << " " << heap[i].code << endl;
}
return 0;
}