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;i<n;i++)ptr.push_back(m);
make_heap(ptr.begin(),ptr.end(),greater<int>());

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 <iostream>
#include<cstdio>   
#include<string>
#include<cstring> 
#include<bits/stdc++.h> 
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<n;i++)cout<<ptr[i]<<" "; //查看   
    int wpl=0;
    for(int i=1;i<n;i++){//i<n 
        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;i<n;i++){
        cin>>m;
        ptr.push_back(m);
    }
    int wpl=calwpl();
    cout<<endl<<"wpl="<<wpl<<endl; 
    return 0;
} 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值