Pagini recente » Cod sursa (job #1313376) | Cod sursa (job #2397016) | Cod sursa (job #2821191) | Cod sursa (job #28220) | Cod sursa (job #514558)
Cod sursa(job #514558)
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <string>
#include <queue>
#include <iostream>
#include <algorithm>
#define MAXN 1000001
using namespace std;
typedef struct treeNode {
struct treeNode *left;
struct treeNode *right;
int poz;
long long weight;
}NOD;
long long sum;
unsigned long long x1 [MAXN];
unsigned long long x2 [MAXN];
queue <NOD*> v1;
queue <NOD*> v2;
int getmin()
{
long long x, y;
if (v1.size() == 0)
return 1;
if (v2.size() == 0)
return 0;
x = v1.front()->weight;
y = v2.front()->weight;
if (x > y)
return 1;
return 0;
}
int parb(NOD *root, unsigned long long x, unsigned long long h)
{
if (root == NULL)
return 1;
if (root->left == NULL && root->right == NULL) {
sum += (h * root->weight);
x1[root->poz] = h;
x2[root->poz] = x;
}
x = x << 1;
parb(root->left, x, h+1);
parb(root->right, x + 1, h+1);
return 1;
}
int main()
{
FILE *f = fopen("huffman.in", "rt");
FILE *g = fopen("huffman.out", "wt");
int n, i, aux;
fscanf(f, "%d" , &n);
for (i = 0; i < n; i++) {
NOD *Node = (NOD *)malloc(sizeof(NOD));
fscanf(f, "%d" , &aux);
Node->weight = aux;
Node->poz = i;
Node->left = NULL;
Node->right = NULL;
v1.push(Node);
}
while (v1.size() + v2.size() > 1) {
NOD *Node = (NOD *)malloc(sizeof(NOD));
Node->weight = 0;
if (getmin()) {
if (!v2.empty()) {
Node->weight += v2.front()->weight;
Node->left = v2.front();
v2.pop();
}
}
else {
if (!v1.empty()) {
Node->weight += v1.front()->weight;
Node->left = v1.front();
v1.pop();
}
}
if (getmin()) {
if (!v2.empty()) {
Node->weight += v2.front()->weight;
Node->right = v2.front();
v2.pop();
}
}
else {
if (!v1.empty()) {
Node->weight += v1.front()->weight;
Node->right = v1.front();
v1.pop();
}
}
if (Node->weight != 0) {
v2.push(Node);
}
}
parb(v2.front(), 0, 0);
fprintf(g, "%lld\n", sum);
for (i = 0; i < n; i++) {
fprintf(g, "%lld %lld\n", x1[i], x2[i]);
}
fclose(f);
fclose(g);
return 0;
}