zoukankan      html  css  js  c++  java
  • [LintCode] Find the Weak Connected Component in the Directed Graph

    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 connected set of a directed graph is a subgraph in which any two vertices are connected by direct edge path.)

    Example

    Given graph:

    A----->B  C
          |  | 
          |  |
          |  |
          v  v
         ->D  E <- F
    

    Return {A,B,D}, {C,E,F}. Since there are two connected component which are{A,B,D} and {C,E,F}

    Note

    Sort the element in the set in increasing order

    Union-Find,并查集!注意fa每次都要重新求,因为fa的值可能在之前的循环中被更新。

     1 /**
     2  * Definition for Directed graph.
     3  * struct DirectedGraphNode {
     4  *     int label;
     5  *     vector<DirectedGraphNode *> neighbors;
     6  *     DirectedGraphNode(int x) : label(x) {};
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     /**
    12      * @param nodes a array of directed graph node
    13      * @return a connected set of a directed graph
    14      */
    15     int find(unordered_map<int, int> &father, int x) {
    16         if (father.find(x) == father.end()) {
    17             father[x] = x;
    18             return x;
    19         }
    20         while (x != father[x]) x = father[x];
    21         return x;
    22     }
    23     vector<vector<int>> connectedSet2(vector<DirectedGraphNode*>& nodes) {
    24         // Write your code here
    25         unordered_map<int, int> father;
    26         int fa, fb, fn;
    27         for (auto &n : nodes) {
    28             for (auto &nn : n->neighbors) {
    29                 fa = find(father, n->label);
    30                 fb = find(father, nn->label);
    31                 if (fa != fb) {
    32                     if (fa > fb) father[fa] = fb;
    33                     else father[fb] = fa;
    34                 }
    35             }
    36         }
    37         unordered_map<int, vector<int>> comp;
    38         for (auto &n : nodes) {
    39             fn = find(father, n->label);
    40             comp[fn].push_back(n->label);
    41         }
    42         vector<vector<int>> res;
    43         for (auto &c : comp) {
    44             sort(c.second.begin(), c.second.end());
    45             res.push_back(c.second);
    46         }
    47         return res;
    48     }
    49 };
  • 相关阅读:
    接口和抽象类的区别
    MFC之ListCtrl动态添加按钮
    C++类间转换之dynamic_cast
    字符串提取
    C++实现快速排序
    MFC中CListCtrl类依靠CImageList贴图并显示不同图像
    北工大耿丹学院16级计科院3班C语言课程助教学期总结
    C语言课程2——我们交流的工具:Coding.net
    salt-minion安装脚本
    zabbix邮件报警脚本
  • 原文地址:https://www.cnblogs.com/easonliu/p/4607300.html
Copyright © 2011-2022 走看看