You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何计算multimap中人际网络链深度?代码返回0问题排查

解决子网深度计算的代码问题

我来帮你分析下当前代码的问题,以及如何修正它来正确计算最长招募链的深度:

现有代码的核心问题

  1. 函数名拼写错误:count_depth_recursive内部调用了不存在的count_recursive,这会直接导致编译或运行错误。
  2. 参数传递的逻辑错误:
    • 你把std::multimap按值传递给递归函数,每次递归都会复制整个容器,不仅效率极低,而且完全没必要,应该用const引用传递。
    • depth参数按值传递时,递归函数里对depth的修改不会影响上层函数,而且你没有跟踪每个分支的最大深度——这就是代码始终返回0的关键原因。
  3. 驱动函数的逻辑错误:在count_depth中,你调用递归时传的是itr->first,但itr是equal_range(id)返回的迭代器,itr->first就是id本身,应该传递itr->second(也就是当前用户的连接对象)。
  4. 缺少最大值跟踪逻辑:当前代码只是盲目递增depth,但没有记录递归过程中出现的最大深度,最后自然得不到正确结果。

修正后的实现方案

我们可以调整思路:让递归函数直接返回当前节点的最大深度——每个节点的深度是**1(自身)**加上其所有连接节点的最大深度,如果没有连接节点则返回1。这样逻辑更清晰,也能正确跟踪最长链。

修正后的代码

#include <iostream>
#include <map>
#include <string>

// 递归计算指定节点的最大深度
int count_depth_recursive(const std::multimap<std::string, std::string>& networkMap, const std::string& id) {
    // 当前节点自身深度至少为1
    int max_depth = 1;
    // 精准找到所有以id为键的连接项,避免遍历整个map
    auto [start, end] = networkMap.equal_range(id);
    
    for (auto itr = start; itr != end; ++itr) {
        // 递归计算子节点的深度,当前节点的深度是子节点深度+1
        int child_depth = count_depth_recursive(networkMap, itr->second);
        if (child_depth + 1 > max_depth) {
            max_depth = child_depth + 1;
        }
    }
    return max_depth;
}

// 驱动函数
int count_depth(const std::multimap<std::string, std::string>& networkMap, const std::string& id) {
    int result = count_depth_recursive(networkMap, id);
    std::cout << result << std::endl;
    return result;
}

// 测试示例
int main() {
    std::multimap<std::string, std::string> network;
    network.insert({"john", "mary"});
    network.insert({"john", "tom"});
    network.insert({"mary", "brad"});
    network.insert({"tom", "Maria"});
    network.insert({"mary", "Eli"});
    network.insert({"brad", "Sofia"});
    
    count_depth(network, "john");   // 输出4,符合预期
    count_depth(network, "Sofia"); // 输出1,符合预期
    return 0;
}

关键改进点说明

  • 用const std::multimap<std::string, std::string>&传递容器,避免不必要的复制,提升效率。
  • 递归函数返回当前节点的最大深度,通过比较所有子节点的深度,动态更新最大值,自然得到最长链的长度。
  • 使用equal_range精准定位当前节点的所有连接项,避免遍历整个map,提升性能。
  • 逻辑更直观:每个节点的深度由自身加上子节点的最长链长度决定,完美匹配你需要的“最长招募链”定义。

内容的提问来源于stack exchange,提问作者cyberbemon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:17:02