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
| void dfs1(int u, const vector<vector<int>>& reverse_edges, vector<bool>& visited, stack<int>& s) { visited[u] = true; for(int v: reverse_edges[u]) { if(!visited[v]) { dfs1(v, reverse_edges, visited, s); } } s.push(u); }
void dfs2(int u, const vector<vector<int>>& edges, vector<bool>& visited, int source, vector<int>& result) { visited[u] = true; result[u] = source; for(int v: edges[u]) { if(!visited[v]) { dfs2(v, edges, visited, source, result); } } }
vector<int> kosaraju(const vector<vector<int>>& edges) { int n = edges.size(); vector<int> result(n);
vector<vector<int>> reverse_edges(n); for(int u=0;u<n;u++) { for(int v: edges[u]) { reverse_edges[v].push_back(u); } }
stack<int> s; do { vector<bool> visited(n, false); for(int u=0;u<n;u++) { if(!visited[u]) { dfs1(u, reverse_edges, visited, s); } } } while(false);
do { vector<bool> visited(n, false); while(!s.empty()) { int u = s.top(); s.pop(); if(!visited[u]) { dfs2(u, edges, visited, u, result); } } } while(false); return result; }
|