【华为机考E卷】-“生成哈夫曼树”题解思路java

算法每一题,成长每一天~

C0E45 生成哈夫曼树

真题链接:【持续更新】2024华为 OD 机试E卷 机考真题库清单(全真题库)

思路

在这里插入图片描述

Java

package com.ccr.paper_f;

import java.util.*;

public class C0E45 {

    static List<Node> nodes = new ArrayList<>();

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        Integer[] arr = new Integer[n];
        for (int i = 0; i < n; i++) {
            arr[i] = in.nextInt();
        }

        Arrays.sort(arr, Comparator.reverseOrder()); // 降序排序
        int sum = Arrays.stream(arr).mapToInt(Integer::intValue).sum();

        Node root = new Node(sum);
        Node node = root; // 根节点
        for (int i = 0; i < arr.length - 2; i++) {
            node = node.addChild(arr[i], false);
        }
        node.addChild(arr[arr.length - 2], true); // 最后两片叶子

        int result = nodes.stream()
                          .filter(x -> x.isLeaf)
                          .mapToInt(x -> x.height * x.value)
                          .sum();
        System.out.println("带权路径长度:" + result);

        // 中序遍历
        midOrder(root);
    }

    // 中序遍历
    static void midOrder(Node node) {
        if (node == null) {
            return;
        }
        midOrder(node.left);
        System.out.print(node.value + " "); // 中序:根节点在中间处理
        midOrder(node.right);
    }


    static class Node {
        int value;
        int height; // 高度
        boolean isLeaf; // 是否为叶子节点

        Node left;
        Node right;

        public Node(int value) {
            this.value = value;
            this.height = 0;
        }

        public Node addChild(int v, boolean end) {
            // 叶子
            Node node = new Node(v);
            node.height = this.height + 1;
            node.isLeaf = true;
            // 同层的非叶子
            Node part = new Node(this.value - v);
            part.height = this.height + 1;
            part.isLeaf = end; // 最后两个都是叶子

            if (v <= this.value / 2) {
                this.left = node;
                this.right = part;
            } else {
                this.right = node;
                this.left = part;
            }

            nodes.add(node);
            nodes.add(part);

            return part; // 返回同级的非叶子节点
        }
    }
}


总结

1、创建 Node 对象,简化创建节点的逻辑。
2、记住 前序中序后序遍历的区别:

方式规则
前序根节点 > 左节点 > 右节点
中序左节点 > 根节点 > 右节点
后序左节点 > 右节点 > 根节点

算法要多练多练多练!!

### 华为OD机考数大雁真题及答案解析 #### 题目描述 给定一个字符串 `croakOfFrogs`,表示不同时间点听到的大雁叫声。每只大雁发出的声音序列严格遵循 "quack" 的顺序。返回能够产生所给字符串的最少大雁数量。如果该字符串不是有效的组合,则返回 `-1`。 条件如下: - 输入字符串长度范围:\( 1 \leq croakOfFrogs.length \leq 10^5 \) - 字符串中的字符仅限于 'q', 'u', 'a', 'c' 或者 'k' #### 解决方案 为了计算最小的大雁数量,可以维护五个计数器来跟踪当前正在发声的不同阶段的大雁数目。每当遇到一个新的起始字母(即 'q'),增加相应计数器;当完成一次完整的 “quack” 声音循环时减少这些计数器。还需要确保任何时候后面的字母不会超过前面的字母的数量,否则就不是一个合法的输入[^1]。 下面是具体的实现方法: ```cpp class Solution { public: int minNumberOfGeese(string croakOfGeese) { unordered_map<char, int> count{{'q', 0}, {'u', 0}, {'a', 0}, {'c', 0}, {'k', 0}}; int max_geese = 0; for (char ch : croakOfGeese) { ++count[ch]; // Check the order of characters to ensure validity. if (!(count['q'] >= count['u'] && count['u'] >= count['a'] && count['a'] >= count['c'] && count['c'] >= count['k'])) { return -1; } // Update maximum number of geese at any point in time. max_geese = std::max(max_geese, *std::max_element(count.begin(), count.end(), [](const auto& p1, const auto& p2) { return p1.second < p2.second; })); // When a full sequence is completed ('quack'), decrement all counters by one. if (ch == 'k') { for (auto& pair : count) { --pair.second; } } } // Ensure no incomplete sequences are left over. for (int val : count.values()) { if (val != 0) return -1; } return max_geese; } }; ``` 此代码通过遍历整个字符串并保持对每个声音部分的追踪来解决问题。它还验证了每次读取新字符后的合法性,并在检测到完整的一轮发音后重置计数器。最后检查是否有未完成的序列存在,如果有则返回错误码 `-1`,否则返回最大并发大雁数量作为结果[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值