Analysis: To determine whether a graph is a strongly connected component, which is solved using the Tarjan algorithm.
#include <iostream> #include <vector> #include <stack>using namespace std;vector<int> map[ 10002];stack<int> tarjan_stack;int low[10002];int dfn[10002];bool vis[10002];int cnt,pos;void Init (int n) {int i; Cnt=pos=0;memset (low,0,sizeof (Low)), memset (dfn,0,sizeof (DFN)); memset (vis,0,sizeof (VIS)); for (i=1;i<=n;i++) Map[i].clear (); while (!tarjan_stack.empty ()) Tarjan_stack.pop ();} void Input (int m) {int i,a,b;for (i=1;i<=m;i++) {cin>>a>>b;map[a].push_back (b);}} void Tarjan (int u) {int I,t;dfn[u]=low[u]=++pos;vis[u]=true;tarjan_stack.push (u); for (I=0;i<map[u].size (); i++) {T =map[u][i];if (!dfn[t]) {Tarjan (t); if (Low[t]<low[u]) low[u]=low[t];} else if (Vis[t] && low[u]>dfn[t]) low[u]=dfn[t];} if (Low[u]==dfn[u]) {cnt++;while (!tarjan_stack.empty ()) {t=tarjan_stack.top (); Tarjan_stack.pop (); vis[t]=false;if (t==u) Break;}}} void Solve (int n,int m) {int i;init (n); Input (m); for (i=1;i<=n;i++)//Cycle prevention is a forest condition can also handle if (!dfn[i]) Tarjan (i); if (cnt==1) Puts ("Yes"); elsepUTS ("No"); int main () {int n,m;while (cin>>n>>m && (n| | M) {Solve (n,m);} return 0;}
HDU ACM 1269 Maze Castle--forward strong connected components (Tarjan algorithm practice)