ZBLOG

#include #include #include using namespace std; struct HuffmanNode { int weight; HuffmanNode* left, * right; HuffmanNode(int leaf) : weight(leaf), left(nullptr), right(nullptr) {} }; struct Compare { b...

你可以通过以下方式修改代码,实现从用户输入获取数据的功能:

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

struct HuffmanNode {
    int weight;
    HuffmanNode* left, * right;
    HuffmanNode(int leaf) : weight(leaf), left(nullptr), right(nullptr) {}
};

struct Compare {
    bool operator()(HuffmanNode* l, HuffmanNode* r) {
        return l->weight > r->weight;
    }
};

int calculateWPL(vector<int>& tree) {
    priority_queue<int, vector<int>, greater<int>> pq(tree.begin(), tree.end());
    
    while (pq.size() > 1) {
        int left = pq.top();
        pq.pop();
        int right = pq.top();
        pq.pop();
        
        int combined = left + right;
        pq.push(combined);
    }
    
    return pq.top();
}

int main() {
    vector<int> tree;
    
    // 获取用户输入的数据
    cout << "请输入一系列整数(以-1结束): ";
    int num;
    while (cin >> num && num != -1) {
        tree.push_back(num);
    }
    
    if (tree.empty()) {
        cout << "未输入任何数据!" << endl;
        return 0;
    }

    int wpl = calculateWPL(tree);
    
    cout << "最优二元树的权: " << wpl << endl;
    
    return 0;
}

在这个修改后的代码中,程序会提示用户输入一系列整数,并且以 -1 结束。然后将用户输入的整数存储到 tree 向量中,最后计算并输出最优二元树的权。如果用户没有输入任何数据,程序会输出相应提示信息。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=14889

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?