题解 | #哈夫曼树#

哈夫曼树

https://www.nowcoder.com/practice/162753046d5f47c7aac01a5b2fcda155

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
    int n, wpl = 0; // wpl 记录最小带权路径长度
    cin >> n;
    vector<int> weight(n);
    for (int i = 0; i < n; i++) {
        cin >> weight[i];
    }
    do {
        sort(weight.begin(), weight.end()); // 按权值由小到大调整weight数组
        int temp = weight[0] + weight[1];
        weight.push_back(temp);
        wpl += temp;
        weight.erase(weight.begin(), weight.begin() + 2);
    } while (weight.size() > 1);
    // 遍历调试
    // for(auto i : weight){
    //     cout << i << " ";
    // }
    cout << wpl << endl;
    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务