使用贪心算法构造 Huffman tree

以下代码是使用贪心算法,构造huffman树的C++实现代码。
来源于我的算法课程实验。

Test Case 测试用例

5
a 0.12
b 0.40
c 0.15
d 0.08
e 0.25

Code 代码

#include<iostream>
#include<string>
#define MAXN 10000
#define INF 10000000000
using namespace std;

typedef struct node{
    char c;
    string code;
    double weight;
    int left_child;
    int right_child;
    int parent;
} ;

node pool [MAXN];

int count;
int index;

void init(){
    index = count;
    for( int i = 0 ; i < MAXN ; i ++ ){
        pool[i].c = '\0';
        pool[i].left_child = -1;
        pool[i].parent = -1;
        pool[i].right_child = -1;
    }
}

void input(){
    cout<<"请依次输入元素和权值,如 a 3"<<endl;
    for( int i = 0 ; i < count ; i ++){
        cin>>pool[i].c;
        cin>>pool[i].weight;
    }
}

void solve(){
    int elements_max_number = (count *2 - 1);
    while(index < elements_max_number){
        int min_index_1 = -1;
        int min_index_2 = -1;
        double min_sum = INF;
        for( int  index_1 = 0 ; index_1<index ; index_1 ++){
            if(pool[index_1].parent == -1){
                for(int index_2 = 0; index_2 < index ; index_2 ++){
                    if(index_1 != index_2 && pool[index_2].parent == -1){
                        if((pool[index_1].weight+pool[index_2].weight)<min_sum){
                            min_index_1 = index_1;
                            min_index_2 = index_2;
                            min_sum = pool[index_1].weight+pool[index_2].weight;
                        }
                    }
                }
            }
        }
        pool[index].c = '\0';
        pool[index].left_child = min_index_1;
        pool[index].right_child= min_index_2;
        pool[index].parent = -1;
        pool[index].weight = min_sum;
        pool[min_index_1].parent = index;
        pool[min_index_2].parent = index;
        index ++;
    }
}

void coding(int flag){
    if(flag == (count * 2 - 2 )){
        pool[flag].code = "";
        coding(pool[flag].left_child);
        coding(pool[flag].right_child);
    }else if(flag != -1){
        int parent = pool[flag].parent;
        if(flag==pool[parent].left_child){
            pool[flag].code = pool[parent].code+"0";
        }else{
            pool[flag].code = pool[parent].code+"1";
        }
        coding(pool[flag].left_child);
        coding(pool[flag].right_child);
    }
}

int main(){
    cout<<"请输入元素个数: ";
    cin>>count;
    if(count && count < MAXN / 2 ){
        init();
        input();
        solve();
        coding(count*2-2);
        system("cls");
        cout<<"---------- HaffMan Code Result ----------"<<endl;
        for(int i = 0 ; i < count ; i ++){
            cout<<"Key :  "<<pool[i].c<<"\tHaffman Code:"<<pool[i].code<<endl;
        }
    }else{
        cout<<"Err..."<<endl;
    }
    return 0;
}
标签: none
返回文章列表 文章二维码
本页链接的二维码
打赏二维码