Pagini recente » Cod sursa (job #1876412) | Cod sursa (job #66685) | Cod sursa (job #2456655) | Cod sursa (job #937559) | Cod sursa (job #769399)
Cod sursa(job #769399)
#include <stdio.h>
#include <queue>
#define int64 long long int
#define arb node*
using namespace std;
typedef struct node {
int64 frecv;
arb left;
arb right;
} node;
class myComp
{
public:
bool operator() (const arb lhs, const arb rhs) const
{
return (lhs->frecv > rhs->frecv);
}
};
priority_queue<arb, vector<arb>, myComp> A;
int n;
int64 S;
void read_() {
scanf("%d", &n);
for (int i = 0; i < n; i++) {
arb El = new node();
scanf("%lld", &(El->frecv));
A.push(El);
}
int Size = A.size();
while (Size > 1) {
arb El1 = A.top();
A.pop();
arb El2 = A.top();
A.pop();
arb Fin = new node();
Fin->frecv = El1->frecv + El2->frecv;
Fin->left = El1;
Fin->right = El2;
A.push(Fin);
S += Fin->frecv;
//printf("%lld %lld -> %lld\n", El1->frecv, El2->frecv, Fin->frecv);
Size--;
}
}
void write_(arb H, int h, int64 val) {
if (H->left == NULL && H->right == NULL) {
printf("%d %lld\n", h, val);
}
if (H->left != NULL) {
write_(H->left, h + 1, val << 1);
}
if (H->right != NULL) {
write_(H->right, h + 1, (val << 1) + 1);
}
}
int main() {
freopen("huffman.in", "r", stdin);
freopen("huffman.out", "w", stdout);
read_();
printf("%lld\n", S);
write_(A.top(), 0, 0);
return 0;
}