llllmz

导航

KY188 哈夫曼树C++

用(优先队列)小根堆,先构建哈夫曼树,然后在递归遍历输出WPL。

 

#include<iostream>
#include<queue>
using namespace std;

struct node{
    int data;
    struct node* left;
    struct node* right;
};
typedef struct node tree;

bool operator < (tree left,tree right){
    if(left.data > right.data ) return true;
    return false;
}

void init_tree(tree* root,int i){
    root->data=i;
    root->left=NULL;
    root->right=NULL;
}

tree* build(tree* x,tree* y){//建树
    tree* root=new tree;
    init_tree(root,x->data+y->data);
    root->left=x;
    root->right=y;
    return root;
}

int WPL(tree* root,int h){
    if(!root) return 0;
    if(!root->left && !root->right) return root->data*h;
    return WPL(root->left,h+1)+WPL(root->right,h+1);
}

int main(){
    int n;
    while(cin >> n){
        priority_queue <tree> heap;
        while(n){//入堆
            int x;
            cin >> x;
            tree tem;
            init_tree(&tem,x);
            heap.push(tem);
            n--;
        }
        while(heap.size()!=1){//建树
            tree* x=new tree;
            *x=heap.top();
            heap.pop();
            tree* y=new tree;
            *y=heap.top();
            heap.pop();
            tree* tem=new tree;
            tem=build(x,y);
            heap.push(*tem);
        }
        tree root=heap.top();
        cout << WPL(&root,0);
    }
    return 0;
}

结果:

 

posted on 2024-01-26 20:16  神奇的萝卜丝  阅读(30)  评论(0)    收藏  举报