Add All UVA - 10954

本文介绍了一种简化版的Huffman树构建方法,通过使用优先队列(最小堆)来解决特定问题,避免了完整的Huffman树构建过程,提高了效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

很简单的一道题目,考察的是huffman树,然而这个题目更简单,不需要建树,直接利用优先队列来进行处理,最后输出最终的结果就可以了,具体实现见如下代码:

#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
#include<cstdio>
#include<deque>
#include<functional>
using namespace std;

int main(){
	int N;
	while (cin >> N){
		if (N == 0) break;
		priority_queue<int, vector<int>, greater<int>> pq;
		for (int i = 0; i < N; i++){
			int t;
			cin >> t;
			pq.push(t);
		}
		int ans = 0;
		for (int i = 0; i < N - 1; i++)
		{
			int a = pq.top();
			pq.pop();
			int b = pq.top();
			pq.pop();
			ans += a + b;
			pq.push(a+b);
		}
		cout << ans << endl;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值