tarjan算法

还是有点晦涩难懂

 

 1 vector<int> low;
 2 vector<int> dfn;
 3 vector<int> father;
 4 vectorint>> g;
 5 int time = 0;
 6 void tarjan(int i, int ifather)
 7 {
 8     father[i] = ifather;
 9     low[i] = time;
10     dfn[i] = time;
11     time++;
12     for (int j = 0; j < g[i].size(); j++)
13     {
14         if (g[i][j] == father[i])
15             continue;
16         else if (dfn[g[i][j]] == -1)
17         {
18             tarjan(g[i][j], i);
19             low[i] = min(low[i], low[g[i][j]]);
20         }
21         else
22             low[i] = min(low[i], dfn[g[i][j]]);  //这里改成    low[i] = min(low[i], min(low[g[i][j]],dfn[g[i][j]])); 如何???
23     }
24     //if (low[i] == dfn[i])    //有向图中且是单向的可以用这个循环求出强连通分量
25     //{
26     //    for (int j = 0; j < dfn.size(); j++)
27     //    {
28     //        if (dfn[j] >= dfn[i])
29     //        {
30     //            cout << j << " ";
31     //        }
32     //    }
33     //    cout << endl;
34     //}
35 }
36 vectorint>> criticalConnections(int n, vectorint>>& connections) {
37     vector<int> use(n, -1);
38     vectorint>> g1(n, vector<int>());
39     g = g1;
40     low = use;
41     dfn = use;
42     father = use;
43     for (auto e : connections)
44     {
45         g[e[0]].push_back(e[1]);
46         g[e[1]].push_back(e[0]);
47     }
48     tarjan(0, -1);
49     vectorint>> ans;
50     for (int i = 0; i < n; i++)
51     {
52         int f = father[i];
53         if (father[i] >= 0 && low[i] > dfn[f])
54         {
55             vector<int> temp;
56             temp.push_back(i);
57             temp.push_back(f);
58             ans.push_back(temp);
59         }
60     }
61     return ans;
62 }

 

你可能感兴趣的:(tarjan算法)