[哈夫曼树]C++ 优先队列(小根堆模拟)

(困了不想写了,直接上代码吧)有时间再来完善

【STL优先队列的哈夫曼树】

#include <iostream>
#include <queue>
#include <vector>

using namespace std;

int main()
{
    priority_queue<int,vector<int>,greater<int>>heap;
    
    int n;
    scanf("%d", &n);
    while (n -- )
    {
        int x;
        cin>>x;
        heap.push(x);
    }
    
    int res=0;
    while(heap.size()>1)
    {
        int a=heap.top();heap.pop();
        int b=heap.top();heap.pop();
        res+=a+b;
        heap.push(a+b);
    }
    cout<<res;
    return 0;
}

【手动模拟小根堆实现哈夫曼】

#include <iostream>
#include <cstdio>

using namespace std;

const int N = 100010;

int h[N], cnt;

void down(int x)
{
	int t = x;
	if (2 * x <= cnt && h[t] > h[2 * x])t = 2 * x;
	if (2 * x + 1 <= cnt && h[t] > h[2 * x + 1])t = 2 * x + 1;
	if (t != x)
	{
		swap(h[t], h[x]);
		down(t);
	}
}

void up(int x)
{
	while (x / 2 && h[x] < h[x / 2])
	{
		swap(h[x],h[x / 2]);
		x >>= 1;
	}
}

void hpush(int x)
{
	cnt++;
	h[cnt] = x;
	up(x);
}

void hpop()
{
	h[1] = h[cnt];
	cnt--;
	down(1);
}

int htop()
{
	return h[1];
}
//全手动模拟哈夫曼树
int main()
{
	int n;
	cin >> n;
	while (n--)
	{
		int x;
		cin >> x;
		hpush(x);
	}

	int res = 0;
	while (cnt > 1)
	{
		int a = htop(); hpop();
		int b = htop(); hpop();
		res += a + b;
		hpush(a + b);
	}
	cout << res << endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值