码迷,mamicode.com
首页 > 其他好文 > 详细

LintCode "Find the Weak Connected Component in the Directed Graph"

时间:2015-10-21 14:08:51      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:

New stuff learnt - Union-Find. Simpler and more elegant than I thought.

class Solution {
    
    unordered_map<int, int> father;
    int find(int val)
    {
    if(!father.count(val))
    {
        father[val] = val;
        return val;
    }
    while(val != father[val]) val = father[val];
    return val;
    }
    void union_(int x, int y) 
    {
        int x_root = find(x), y_root = find(y);
        father[min(x_root, y_root)] = max(x_root, y_root);
    }
public:
    /**
     * @param nodes a array of directed graph node
     * @return a connected set of a directed graph
     */
    vector<vector<int>> connectedSet2(vector<DirectedGraphNode*>& nodes) 
    {
    // Sort first
    sort(nodes.begin(), nodes.end(),
             [](const DirectedGraphNode* a, const DirectedGraphNode* b) {
                return a->label < b->label;
             });
    
    // Union and Find
    for (auto &n : nodes) 
    {
        for(auto &&nn : n->neighbors)
        {
        int fn = find(n->label);
        int fnn= find(nn->label);
        if(fn != fnn)
            union_(fn, fnn);
        }
    }
    
    // Grouping
    unordered_map<int, vector<int>> group;
        for (const auto& node : nodes) {
            group[find(node->label)].emplace_back(node->label);
        }
        
        // Output
    vector<vector<int>> ret;
    for (auto& kvp : group) {
            ret.emplace_back(move(kvp.second));
        }
        return ret;
    }
};

LintCode "Find the Weak Connected Component in the Directed Graph"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4897482.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!