1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| class Solution { public: void Tarjan(vector<vector<int>>& g, int st, vector<int>& parent, vector<int>& low, vector<int>& dfsNo, int no, set<int>& cutPoints, vector<vector<int>>& cutEdges) { int rootChildNum = 0; low[st] = dfsNo[st] = no; for(auto neighbor : g[st]) { if(-1 != dfsNo[neighbor]) { if(parent[st] != neighbor) { low[st] = min(low[st], dfsNo[neighbor]); } } else { parent[neighbor] = st; ++rootChildNum; ++no; Tarjan(g, neighbor, parent, low, dfsNo, no, cutPoints, cutEdges); low[st] = min(low[st], low[neighbor]); if(-1 != parent[st] && dfsNo[st] <= low[neighbor]) { cutPoints.insert(st); } if(dfsNo[st] < low[neighbor]) { cutEdges.emplace_back(vector<int>{st, neighbor}); } } } if(parent[st] == -1 && rootChildNum >= 2) { cutPoints.insert(st); } }
vector<vector<int>> criticalConnections(int n, vector<vector<int>>& connections) { vector<vector<int>> g(n); for(auto e : connections) { g[e[0]].push_back(e[1]); g[e[1]].push_back(e[0]); }
vector<int> dfsNo(n, -1); vector<int> low(n, -1); vector<int> parent(n, -1); int no = 0;
set<int> cutPoints; vector<vector<int>> cutEdges; dfsNo[0] = 0; Tarjan(g, 0, parent, low, dfsNo, no, cutPoints, cutEdges); for(auto i : cutPoints) { cout << i << " "; } cout << "low: "; for(auto i : low) { cout << i << " "; } cout << "\ndfsNo: "; for(auto no : dfsNo) { cout << no << " "; } return cutEdges; } };
|