题解 | 哈夫曼树(bupt)
哈夫曼树
https://www.nowcoder.com/practice/162753046d5f47c7aac01a5b2fcda155
#include <iostream> #include <vector> #include <algorithm> using namespace std; bool compare(int x, int y) { return x>y; } int main() { int n; while (cin >> n) { vector<int> set; for(int i=0; i<n; i++) { int weight; cin >> weight; set.push_back(weight); } int num=0; while(set.size()>1) { sort(set.begin(),set.end(),compare); //降序排序 int pos=set.size()-1; int sum=set[pos]+set[pos-1]; //带权路径总长度等于非叶节点权值之和 num+=sum; set.pop_back(); set.pop_back(); set.push_back(sum); } cout << num << endl; } }#考研#