文章

74

粉丝

0

获赞

98

访问

9.0k

头像
哈夫曼树 题解(priority_queue解决):
P1382 北京邮电大学/兰州大学机试
发布于2025年8月11日 19:32
阅读数 130

#include<bits/stdc++.h>
using namespace std;

struct Node{
	int x;
	Node(int a){x = a;}
};

bool operator<(const Node &a, const Node &b){
	return a.x > b.x;
}

int main(){
	int n; 
	
	while(cin >> n){
	
		priority_queue<Node> pq;
		while(n --){
			int t; cin >> t;
			pq.push(t);
		}

		int res = 0;
		while(pq.size() > 1){
			int x = pq.top().x;
			pq.pop();
			int y = pq.top().x;
			pq.pop();
			res += (x + y);
			pq.push(Node{(x + y)});
		}

		cout << res << endl;
	}
		
	return 0;
}

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发