LintCode 432: Find the Weak Connected Component in the Directed Graph (并查集经典题)

本文探讨了如何在有向图中寻找弱连通分量的方法,主要介绍了使用并查集算法进行高效求解的过程。通过具体实例说明了并查集在处理此类问题上的优势,并提供了详细的代码实现。
  1. Find the Weak Connected Component in the Directed Graph

Find the number Weak Connected Component in the directed graph. Each node in the graph contains a label and a list of its neighbors. (a weak connected component of a directed graph is a maximum subgraph in which any two vertices are connected by direct edge path.)

Example
Example 1:

Input: {1,2,4#2,4#3,5#4#5#6,5}
Output: [[1,2,4],[3,5,6]]
Explanation:

  1----->2        3-->5
   \     |        ^
    \    |        |
     \   |        6
      \  v
       ->4

Example 2:

Input: {1,2#2,3#3,1}
Output: [[1,2,3]]
Clarification
graph model explaination:
https://www.lintcode.com/help/graph

Notice
Sort the elements of a component in ascending order.

解法1:Union-Find
这题最好用并查集做。用BFS/DFS也可以做,但因为是有向图,必须把有向链接转换成无向链接才行。为什么呢?
比如说Input: {1,2,4#2,4#3,5#4#5#6,5}
Output: [[1,2,4],[3,5,6]]
Explanation:

1----->2          3-->5
   \     |        ^
    \    |        |
     \   |        6
      \  v
       ->4

如果用BFS/DFS的话,到了3就找不到6了,所以没法知道3和6是一组。
注意:
1)merge()的写法要注意。特别是最后是father[fatherX]=fatherY。不能写成father[x]=fatherY,这样x是连到了fatherY,但是fatherX到fatherY的链接就断了。为了简单起见,可以将merge(int x, int y)写成这样的模板:

void merge (int x, int y) {
    int x = find(x);
    int y = find(y);
    if (x != y) father[x]=y;
}
  1. 当union完成后,以input={1,2,3,4#2,3#3#4}为例,其各个节点的father如下。
    1’s father is 3
    2’s father is 4
    3’s father is 4
    4’s father is 4
    此时并不能看出它们都是同一个father,所以最后的for循环里面还是必须用find(x)来找到各个节点的最上层祖宗,不能直接用father[x]。

  2. father在这里必须用map,不能直接用数组,因为label可能很大(不一定是1,2,3,4,5),另外也可能是负数。
    代码如下:

/**

  • Definition for Directed graph.
  • struct DirectedGraphNode {
  • int label;
    
  • vector<DirectedGraphNode *> neighbors;
    
  • DirectedGraphNode(int x) : label(x) {};
    
  • };
    */

class Solution {
public:
/*
* @param nodes: a array of Directed graph node
* @return: a connected set of a directed graph
/
vector<vector> connectedSet2(vector<DirectedGraphNode
> nodes) {
int n = nodes.size();

    //initialize, each node's father is itself
    for (auto node : nodes) {
        father[node->label] = node->label;
    }
    
    //union
    for (int i = 0; i < n; ++i) {
        for (auto neighbor : nodes[i]->neighbors) {
            merge(nodes[i]->label, neighbor->label);
        }
    }
    map<int, vector<int>> component; //father, children
    for (int i = 0; i < n; ++i) {
        int findFather = find(father[nodes[i]->label]);
        if (component.find(findFather) == component.end()) {
            component[findFather] = vector<int>();
        }
        
        component[findFather].push_back(nodes[i]->label); 
    }
    
    for (auto m : component) {
        result.push_back(m.second);
    }
    return result;
}

private:
map<int, int> father;
//vector father; //wrong, because label can be negative
vector<vector> result;

int find(int x) {
    if (x == father[x]) {
        return x;
    }
    father[x] = find(father[x]);
    return father[x];
}

void merge(int x, int y) {
    int fatherX = find(x);  //not fatherX = father[x];
    int fatherY = find(y);
    if (fatherX != fatherY) {
        father[fatherX] = fatherY;   //not father[y]
    }
}

};

内容概要:本文介绍了一个基于冠豪猪优化算法(CPO)的无人机三维路径规划项目,利用Python实现了在复杂三维环境中为无人机规划安全、高效、低能耗飞行路径的完整解决方案。项目涵盖空间环境建模、无人机动力学约束、路径编码、多目标代价函数设计以及CPO算法的核心实现。通过体素网格建模、动态障碍物处理、路径平滑技术和多约束融合机制,系统能够在高维、密集障碍环境下快速搜索出满足飞行可行性、安全性与能效最优的路径,并支持在线重规划以适应动态环境变化。文中还提供了关键模块的代码示例,包括环境建模、路径评估和CPO优化流程。; 适合人群:具备一定Python编程基础和优化算法基础知识,从事无人机、智能机器人、路径规划或智能优化算法研究的相关科研人员与工程技术人员,尤其适合研究生及有一定工作经验的研发工程师。; 使用场景及目标:①应用于复杂三维环境下的无人机自主导航与避障;②研究智能优化算法(如CPO)在路径规划中的实际部署与性能优化;③实现多目标(路径最短、能耗最低、安全性最高)耦合条件下的工程化路径求解;④构建可扩展的智能无人系统决策框架。; 阅读建议:建议结合文中模型架构与代码示例进行实践运行,重点关注目标函数设计、CPO算法改进策略与约束处理机制,宜在仿真环境中测试不同场景以深入理解算法行为与系统鲁棒性。
### C++中 `bad_weak_ptr` 异常的原因与解决方案 在C++中,`std::bad_weak_ptr` 是一个异常类,定义在头文件 `<memory>` 中。当尝试通过一个无效的 `std::weak_ptr` 来访问 `std::shared_ptr` 时,会抛出此异常。这种无效性通常发生在 `std::weak_ptr` 所指向的对象已经被销毁的情况下,而此时调用了 `std::weak_ptr::lock()` 方法[^3]。 以下是对该异常的原因和解决方案的详细分析: #### 1. 原因分析 `std::bad_weak_ptr` 异常的根本原因是 `std::weak_ptr` 的设计机制。`std::weak_ptr` 并不控制对象的生命周期,它只提供一种观察 `std::shared_ptr` 管理的对象的方式。如果 `std::shared_ptr` 被销毁或其引用计数降为零,则 `std::weak_ptr` 将无法再访问该对象。此时,调用 `std::weak_ptr::lock()` 将返回一个空的 `std::shared_ptr`,并且如果直接假设返回值有效而不进行检查,就会导致异常抛出[^4]。 #### 2. 解决方案 为了避免 `std::bad_weak_ptr` 异常的发生,可以采取以下措施: - **检查 `std::weak_ptr::lock()` 的返回值是否为空** 在使用 `std::weak_ptr::lock()` 返回的 `std::shared_ptr` 之前,应始终检查其是否为空。这是最常见且推荐的做法。代码示例如下: ```cpp std::weak_ptr<int> weakPtr; // 假设 weakPtr 已被初始化 std::shared_ptr<int> sharedPtr = weakPtr.lock(); if (sharedPtr) { // 对象仍然存在,可以安全地使用 *sharedPtr = 42; } else { // 对象已被销毁,执行其他逻辑 std::cerr << "Object has been destroyed." << std::endl; } ``` - **避免直接使用可能抛出异常的代码路径** 如果程序逻辑允许,可以通过设计避免在 `std::weak_ptr` 指向的对象已销毁时继续执行相关操作。例如,在某些场景下,可以选择忽略这种状态,而不是依赖异常处理机制[^5]。 - **使用自定义封装** 可以创建一个封装类来简化对 `std::weak_ptr` 的管理,自动处理对象是否存在的情况。这种方式可以减少重复代码并提高可维护性。 #### 3. 示例代码 以下是一个完整的示例,展示如何正确处理 `std::weak_ptr` 和避免 `std::bad_weak_ptr` 异常: ```cpp #include <iostream> #include <memory> int main() { std::shared_ptr<int> shared = std::make_shared<int>(10); std::weak_ptr<int> weak = shared; // 模拟 shared_ptr 被销毁 shared.reset(); // 安全地访问 weak_ptr std::shared_ptr<int> lockedPtr = weak.lock(); if (lockedPtr) { std::cout << "Value: " << *lockedPtr << std::endl; } else { std::cout << "The object has been destroyed." << std::endl; } return 0; } ``` #### 4. 总结 `std::bad_weak_ptr` 异常通常是因为未正确处理 `std::weak_ptr` 的生命周期问。通过在调用 `std::weak_ptr::lock()` 后检查返回值是否为空,可以有效避免此类异常的发生。此外,合理设计程序逻辑,尽量减少对已销毁对象的依赖,也是预防问的重要手段。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值