[数据结构]计算WPL 解题报告

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 
#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;jhufmanTree[j].weight){
                    max1 = hufmanTree[j].weight;
                    s1 = j;
                    
                }
                
            }
        }
        for(int j =1;j 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;
}

你可能感兴趣的:([数据结构]计算WPL 解题报告)