Problem Description
Huffman編碼是通信系統(tǒng)中常用的一種不等長(zhǎng)編碼,它的特點(diǎn)是:能夠使編碼之后的電文長(zhǎng)度最短。
輸入:
第一行為要編碼的符號(hào)數(shù)量n
第二行~第n+1行為每個(gè)符號(hào)出現(xiàn)的頻率
輸出:
對(duì)應(yīng)哈夫曼樹的帶權(quán)路徑長(zhǎng)度WPL
測(cè)試輸入
5
7
5
2
4
9
測(cè)試輸出
WPL=60
AcCode
//
// main.cpp
// 計(jì)算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;
}