比较间的哈夫曼题目
一:合并果子(经典问题)
题目来源:
果子
priority_queue<long long, vector<long long>, greater<long long>>q;
greater< long long>表示数小的优先级高
#include<bits/stdc++.h>
using namespace std;
priority_queue<long long, vector<long long>, greater<long long>>q;
// 定义优先队列q
int main() {
int n;
long long temp,x,y,ans = 0;
cin>>n;
for(int i = 0; i < n; i++) {
cin>>temp;
q.push(temp);
}
while(q.size() > 1) {
x = q.top();
q.pop();
y = q.top();
q.pop();
q.push(x + y);
ans += x + y;
}
cout<<ans;
}
二:问题C:哈夫曼树
哈夫曼树
这道题易错在队列中本来还有一个元素,所以在每次之前先判断是否非空,不空的话让他弹出
#include<bits/stdc++.h>
using namespace std;
priority_queue<long long, vector<long long>, greater<long long>>q;
// 定义优先队列q
int main() {
int n;
long long temp,x,y,ans;
while(scanf("%d",&n) != EOF) {
while(!q.empty()) {
q.pop();
}
for(int i = 0; i < n; i++) {
cin>>temp;
q.push(temp);
}
ans = 0;
while(q.size() > 1) {
x = q.top();
q.pop();
y = q.top();
q.pop();
q.push(x + y);
ans += x + y;
}
cout<<ans<<endl;
}
}