[leetcode] 1192 critical-connections-in-a-network

https://leetcode.com/contest/weekly-contest-154/problems/critical-connections-in-a-network/

class Solution {
public:
    vectorint>> res;
    int index = 0; // 访问序号
    vector<int> dfn; // 当前访问的序号
    vector<int> low; // 当前节点&其子树 最早访问的序号

    vectorint>> graph;
    void tarjan(int cur, int last)
    {
        low[cur] = dfn[cur] = index++; // 分配一个序号
        for (const auto& next : graph[cur])
        {
            if(next == last) continue; // 避免重复访问         
            if (dfn[next] == -1) 
            {
                tarjan(next, cur);  // 没有访问过,继续搜索
                low[cur] = min(low[cur], low[next]); // 更新最早序号
                if(low[next] > dfn[cur]) // 新的节点的low已经大于当前节点的序号,说明已经不在同一个强联通分量里了
                {
                    res.push_back({cur, next}); // 加入到结果中
                }
            }
            else
            {
                low[cur] = min(low[cur], dfn[next]);// 访问过了,直接更新
                //low[cur] = min(low[cur], low[next]);  -> I think this is right !
            }
        }
    }

    vectorint>> criticalConnections(int n, vectorint>>& connections) {
        dfn.resize(n, -1);
        low.resize(n, -1);    
        graph.resize(n);
        for (int i = 0; i < connections.size(); i++)
        {
            vector<int>& c = connections[i];
            int v1 = c[0];
            int v2 = c[1];
            graph[v1].push_back(v2);
            graph[v2].push_back(v1);
        }
        tarjan(0, -1); // 处在同一个强联通分量中节点, 最终会得到相同的low值
      //  for(int i = 0;i < n;i++) cout << low[i] << " " << dfn[i] << endl;
        return res;
    }
};

 

转载于:https://www.cnblogs.com/fish1996/p/11522072.html

你可能感兴趣的:([leetcode] 1192 critical-connections-in-a-network)