Problem Description
Huffman编码是通信系统中常用的一种不等长编码,它的特点是:能够使编码之后的电文长度最短。
输入:
第一行为要编码的符号数量n
第二行~第n+1行为每个符号出现的频率
输出:
对应哈夫曼树的带权路径长度WPL
测试输入
5
7
5
2
4
9
测试输出
WPL=60
AcCode
//
// main.cpp
// 计算WPL
//
// Created by jetviper on 2017/3/26.
// Copyright © 2017年 jetviper. All rights reserved.
//
#include <stdio.h>
#define true 1
#define false 0
typedef struct {
unsigned int weight;
unsigned int parent,leftChild,rightChild;
}HTNode, *HuffmnTree;
HTNode hufmanTree[100000];
int main() {
int num,m;
scanf("%d",&num);
m = 2 * num -1;
for(int i=1;i<=num;i++){
scanf("%d",&hufmanTree[i].weight);
hufmanTree[i].parent = 0;
hufmanTree[i].leftChild = 0;
hufmanTree[i].rightChild = 0;
}
int s1,s2,max1,max2,iset1,iset2;
for(int i=num+1;i<=m;i++){
max1 =0,max2=0;
iset1 =0,iset2=0;
for(int j=1;j<i;j++){
if(hufmanTree[j].parent == 0){
if(iset1 == 0){
max1 = hufmanTree[j].weight;
s1 = j;
iset1 = 1;
continue;
}
if(max1>hufmanTree[j].weight){
max1 = hufmanTree[j].weight;
s1 = j;
}
}
}
for(int j =1;j<i;j++){
if(j == s1)continue;
if(hufmanTree[j].parent == 0) {
if (iset2 == 0) {
max2 = hufmanTree[j].weight;
s2 = j;
iset2 = 1;
continue;
}
if (max2 > hufmanTree[j].weight) {
max2 = hufmanTree[j].weight;
s2 = j;
}
}
}
hufmanTree[s1].parent = i;
hufmanTree[s2].parent = i;
hufmanTree[i].leftChild = s1;
hufmanTree[i].rightChild = s1;
hufmanTree[i].weight = hufmanTree[s1].weight + hufmanTree[s2].weight;
}
int result =0;
for(int i =1;i<=num;i++){
if(hufmanTree[i].parent != 0){
int temp= hufmanTree[i].parent;
int count = 1;
while(1){
if(hufmanTree[temp].parent!=0){
temp = hufmanTree[temp].parent;
count++;
continue;
}
else break;
}
result += count * hufmanTree[i].weight;
}
}
printf("WPL=%d\n",result);
return 0;
}
网友评论