输入
abbccc$
输出
9
样例输入 Copy
hello world$
样例输出 Copy
32
struct BiTNode* lchild, * rchild;
typedef struct linkNode {
int createForest(Forest& forest)
for (int i = 0; i < 128; i++) {
tree = (BiTNode*)malloc(sizeof(BiTNode));
LinkNode* newNode = (LinkNode*)malloc(sizeof(LinkNode));
void sortForest(Forest forest)
LinkNode* p = forest->next;
BiTree* trees = (BiTree*)malloc(sizeof(BiTree) * MAX_SIZE);
trees[count++] = p->tree;
for (int i = 0; i < count - 1; i++) {
for (int j = 0; j < count - i - 1; j++) {
if (trees[j]->weight > trees[j + 1]->weight) {
for (int i = 0; i < count; i++) {
BiTree createHuffmanTree(Forest forest)
while (forest->next->next != NULL) {
BiTree t1 = forest->next->tree;
BiTree t2 = forest->next->next->tree;
BiTree newNode = (BiTree)malloc(sizeof(BiTNode));
newNode->weight = t1->weight + t2->weight;
LinkNode* newLinkNode = (LinkNode*)malloc(sizeof(LinkNode));
newLinkNode->tree = newNode;
newLinkNode->next = forest->next->next->next;
forest->next->next->next = newLinkNode;
forest->next = forest->next->next->next;
return forest->next->tree;
void calculateEncodingLength(BiTNode* root, int depth, int& totalLength) {
if (!root->lchild && !root->rchild) {
totalLength += depth * root->weight;
calculateEncodingLength(root->lchild, depth + 1, totalLength);
calculateEncodingLength(root->rchild, depth + 1, totalLength);
Forest forest = (linkNode*)malloc(sizeof(linkNode));
forest->tree = (BiTNode*)malloc(sizeof(BiTNode));
forest->tree->data = '$';
BiTree root = createHuffmanTree(forest);
calculateEncodingLength(root, 0, totalLength);
printf("%d\n",totalLength);