Strong connected component Decomposition Tarjan algorithm (HDU 1269)
Test instructions
A forward graph with n points m edges is given to determine if the graph has only one strong connected component.
Limit:
0 <= N <= 10000
0 <= M <= 100000
Ideas:
The Tarjan algorithm decomposes strong connected components.
/* Strongly connected component decomposition Tarjan algorithm (HDU 1269) test instructions: A forward graph with n points m edge is given to determine if the graph has only one strong connected component. Limit: 0 <= N <= 10000 0 <= M <= 100000 * * #include <iostream> #include <cstdio> #include <stack> #i Nclude<vector> #include <cstring>using namespace std;const int max_v = 1e5+5; #define PB push_backvector< Int> g[max_v];stack<int> tarjan_stack;int Dfn[max_v], low[max_v];int tarjan_set[max_v];bool In_stack[MAX_V] ; int scc_cnt, tarjan_cnt;void tarjan (int u) {dfn[u] = Low[u] = ++tarjan_cnt;tarjan_stack.push (u); in_stack[u] = True;for ( int i = 0; I < g[u].size (); ++i) {int ch = g[u][i];if (! Dfn[ch]) {Tarjan (CH); Low[u] = min (Low[u], low[ch]);} else if (In_stack[ch]) {Low[u] = min (Low[u], dfn[ch]);}} if (dfn[u] = = Low[u]) {int tmp;++scc_cnt;do{tmp = Tarjan_stack.top (); Tarjan_stack.pop (); in_stack[tmp] = False;tarjan_ SET[TMP] = scc_cnt;} while (tmp! = u);}} void Add_edge (int u,int v) {G[u]. PB (v);} void Init_tarjan (int n) {scc_cnt = tarjan_cnt = 0;memset (DFN, 0, sizeof (DFN)), memset (low, 0, sizeof (LOW)); memset (in_stack, 0, sizeof (in_stack)), memset (tarjan_set, 0, sizeof (tarjan_set)); for (int i = 0; I <= N; ++i) g[i].c Lear ();} The ordinal of the point starts with 0 void Gao (int n) {for (int i = 0; i < n; ++i) {if (! Dfn[i]) Tarjan (i);} for (int i = 1; i < n; ++i) {if (Tarjan_set[i]! = Tarjan_set[i-1]) {puts ("No"); return;}} Puts ("Yes");} int main () {int n, m;while (scanf ("%d%d", &n, &m) && (n | | m)) {Init_tarjan (n); for (int i = 0; i < m; ++i) { int u, v;scanf ("%d%d", &u, &v); Add_edge (u-1, V-1);} Gao (n);} return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Strong connected component Decomposition Tarjan algorithm (HDU 1269)