ACM-数据结构-哈夫曼树 wpl计算(最小堆heap+vector)

题意:给你一个n,接下来输入n个数字:表示对应字符的出现次数(即权值),依此权值大小,建成哈夫曼树(最小堆),求哈夫曼树的wpl。

STL的heap的应用
一·头文件 algorithm
二·STL中与堆相关的4个函数
1.建立堆make_heap()

make_heap(_First, _Last, _Comp)
默认是建立最大堆的。对int类型,可以在第三个参数传入greater<int>()得到最小堆。自己定义的结构体要自己定义操作(>).
vector<int>ptr;
for(int i=0;iint>());

2.在堆中添加数据push_heap()

push_heap (_First, _Last)
要先在容器中加入数据,再调用push_heap ()
ptr.push_back(w1+w2);
push_heap(ptr.begin(),ptr.end(),greater<int>());

3.在堆中删除数据pop_heap()

pop_heap(_First, _Last)
要先调用pop_heap()再在容器中删除数据
int w1=ptr[0];//最小堆的第一个是最小值
pop_heap(ptr.begin(),ptr.end(),greater<int>());
ptr.pop_back();

4.堆排序sort_heap()

sort_heap(_First, _Last)
排序之后就不再是一个合法的heap了
注意使用最小堆排序后是递减数组,要得到递增数组,可以使用最大堆。

样例:

7
1 1 1 3 3 6 6

代码:

#include 
#include   
#include
#include 
#include 
using namespace std;
int n,m,l,k;
const int maxn=260;//zifu
vector<int>ptr;
int calwpl(){ 
    make_heap(ptr.begin(),ptr.end(),greater<int>());
    //for(int i=0;i
    int wpl=0;
    for(int i=1;i//i
        int w1=ptr[0];
        pop_heap(ptr.begin(),ptr.end(),greater<int>());
        ptr.pop_back();
        int w2=ptr[0];
        pop_heap(ptr.begin(),ptr.end(),greater<int>());
        ptr.pop_back();
        printf("w1=%d w2=%d\n",w1,w2);
        wpl+=w1+w2;
        ptr.push_back(w1+w2);
        push_heap(ptr.begin(),ptr.end(),greater<int>());
    }
    return wpl;
}
int main(){
    ios::sync_with_stdio(false);
    freopen("1.txt","r",stdin);
    cin>>n;
    for(int i=0;icin>>m;
        ptr.push_back(m);
    }
    int wpl=calwpl();
    cout<"wpl="<return 0;
} 

你可能感兴趣的:(算法题解)