北京邮电大学机试 哈夫曼树 Easy *第一次遇到赫夫曼树,用优先队列确实有奇效

基本思想:

优先队列保证数值最小;

 

关键点:

无;

 

#include<iostream>
#include<string>
#include<vector>
#include<queue>
using namespace std;


int main() {
	int n;
	int a;
	while (cin >> n) {
		int cnt = 0;
		priority_queue<int, vector<int>, greater<int> >pq;
		for (int i = 0; i < n; i++) {
			cin >> a;
			pq.push(a);
		}
		while (pq.size() != 1) {
			int a = pq.top();
			pq.pop();
			int b = pq.top();
			pq.pop();
			cnt += a + b;
			pq.push(a + b);
		}
		cout << cnt << endl;
	}
}

  

posted @ 2020-03-12 20:08  暮云林凌  阅读(190)  评论(0)    收藏  举报