zoukankan      html  css  js  c++  java
  • 九度 1172:哈夫曼树

    题目描述:

    哈夫曼树,第一行输入一个数n,表示叶结点的个数。需要用这些叶结点生成哈夫曼树,根据哈夫曼树的概念,这些结点有权值,即weight,题目需要输出所有结点的值与权值的乘积之和

    思路

    1. 构建哈夫曼树然后 topDown 遍历即可

    2. 也可以不显式的创建树. 所有树叶点的和即为所求(根节点以外)

    代码 STL priority_queue 自定类型不会用

    #include <iostream>
    #include <stdio.h>
    #include <queue>
    using namespace std;
    
    class Node {
    public:
        int value;
        Node *left, *right;
    
        Node(int _value) {
            value = _value;
        } 
        Node() {
            Node(0);
        }
        bool operator<(const Node &ths) const {
            return this->value < ths.value;
        }
    };
    
    int n;
    int res;
    
    void calculate(Node *root, int depth) {
        if(root->left == NULL && root->right == NULL) {
            res += root->value*depth;
            return;
        }
        calculate(root->left, depth+1);
        calculate(root->right, depth+1);
    }
    
    int main() {
        freopen("testcase.txt", "r", stdin);
        while(scanf("%d", &n) != EOF) {
            res = 0;
            priority_queue<Node*> record;
    
            int val;
            for(int i = 0; i < n; i ++) {
                scanf("%d", &val);
                record.push(new Node(val));
            }
    
            while(record.size() != 1) {
                Node *node1 = record.top();
                record.pop();
                Node *node2 = record.top();
                record.pop();
    
                Node *newNode = new Node(node1->value + node2->value);
                newNode->left = node1;
                newNode->right = node2;
                record.push(newNode);
            }
    
            calculate(record.top(), 0);
    
            cout << res << endl;
        }
        return 0;
    }
  • 相关阅读:
    残缺的字符串
    [BZOJ3513: [MUTC2013]idiots]
    FFT感性瞎扯
    Quartz框架简介
    异常状态码总结
    【SSM】拦截器的原理、实现
    FastDFS实现文件上传下载实战
    分布式文件系统FastDFS设计原理(转)
    FastDFS简介
    【设计模式】观察者模式
  • 原文地址:https://www.cnblogs.com/xinsheng/p/3592375.html
Copyright © 2011-2022 走看看