Pagini recente » Cod sursa (job #1277766) | Cod sursa (job #60046) | Cod sursa (job #1067648) | Cod sursa (job #569667) | Cod sursa (job #514554)
Cod sursa(job #514554)
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <string>
#include <queue>
#include <iostream>
using namespace std;
typedef struct treeNode {
struct treeNode *left;
struct treeNode *right;
int weight;
}NOD;
long long sum;
vector <int> x1, x2;
queue <NOD*> v1;
queue <NOD*> v2;
int getmin(queue <NOD*> v1, queue <NOD*> v2)
{
int 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, int x, int h)
{
if (root == NULL)
return 1;
if (root->left == NULL && root->right == NULL) {
sum += (h * root->weight);
x1.push_back(h);
x2.push_back(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->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(v1, v2)) {
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(v1, v2)) {
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 (vector <int>::iterator it = x1.begin(), it2 = x2.begin(); it != x1.end() && it2 != x2.end(); it++, it2++)
fprintf(g, "%d %d\n", *it, *it2);
fclose(f);
fclose(g);
return 0;
}