Pagini recente » Cod sursa (job #2034679) | Cod sursa (job #2103384) | Istoria paginii onis-2016/solutii-runda-1 | Cod sursa (job #105896) | Cod sursa (job #902568)
Cod sursa(job #902568)
#include <cstdio>
#include <queue>
#include <set>
#include <vector>
using namespace std;
struct node {
node *left;
node *right;
int val;
node(int _val, node *_left, node *_right):
val(_val), left(_left), right(_right) {}
};
struct node_comp {
bool operator()(const node *a, const node *b) {
return a->val > b->val;
}
};
void dfs(node *root, int d, int val)
{
if (root->left == NULL && root->right == NULL)
return;
dfs(root->left, d + 1, val << 1);
dfs(root->right, d + 1, (val << 1) + 1);
printf("%d %d\n", d, val);
}
int main()
{
freopen("huffman.in", "r", stdin);
freopen("huffman.out", "w", stdout);
int n;
scanf("%d", &n);
priority_queue<node *, vector<node *>, node_comp> tree;
for (int i = 0; i < n; ++i) {
int v;
scanf("%d", &v);
tree.push(new node(v, NULL, NULL));
}
node *root;
int total_value = 0;
while (true) {
node *low = tree.top();
tree.pop();
if (tree.empty()) {
root = low;
break;
}
node *next = tree.top();
tree.pop();
tree.push(new node(low->val + next->val, low, next));
total_value += low->val;
total_value += next->val;
}
printf("%d\n", total_value);
dfs(root, 1, 1);
return 0;
}