Maze Castle
Time limit:2000/1000 MS (java/others) Memory limit:65536/32768 K (java/others)
Total submission (s): 8487 Accepted Submission (s): 3797
Problem description in order to train the sense of direction, Gardon built a large castle, there are N rooms (n<=10000) and M-channel (m<=100000), each channel is one-way, That is, if a channel is said to be connected to room A and room B, only the room B can be reached by this passage, but it does not mean that it can be reached by Room B. Gardon need to ask you to write a procedure to confirm whether any two rooms are interconnected, namely: for arbitrary I and J, there is at least one path can be from room I to room J, there is a path can be from room J to room I.
The input input contains more than one set of data, the first line of inputs has two numbers: N and M, and the next m row has two numbers a and B, indicating that a passage can come from room A to room B. The file ends with two 0.
Output for each set of data entered, if any two rooms are connected to each other, outputs "Yes", otherwise output "No".
Sample Input3 31 22 33 13 31 22 33 20 0
Sample Outputyesno
Authorgardon
Sourcehdu 2006-4 Programming Contest
#include <iostream> #include <cstdio> #include <cstring> #include <string> #include <cmath > #include <cstdlib> #include <algorithm> #include <queue> #include <vector> #include < stack>using namespace std; #define MAXN 10000+10vector<int> mp[maxn];stack<int> s;int n,m,dfs[maxn],low [Maxn];bool isstack[maxn];int use[maxn];int top,newflag;void init () {memset (isstack,0,sizeof (isstack)); memset (use,0,sizeof (use)); memset (dfs,0,sizeof (DFS)); memset (low,0,sizeof (Low)); for (int i=0;i<maxn;i++) mp[i].clear (); while (!s.empty ()) S.pop (); newflag=0; Top=0;} void Tarjan (int u) {dfs[u]=low[u]=++top; Isstack[u]=1; S.push (U); for (int x=0;x<mp[u].size (); x + +) {int v=mp[u][x]; if (! Dfs[v]) {Tarjan (v); if (Low[v]<low[u]) low[u]=low[v]; } else if (Isstack[v]&&dfs[v]<low[u]) {LOW[U]=DFS[V]; } } if (Dfs[u]==low[u]) {newflag++; int x; do {x=s.top (); isstack[x]=0; Use[x]=newflag; S.pop (); }while (X!=u); } return; int main () {int x, y; while (scanf ("%d%d", &n,&m)!=eof) {if (n==0&&m==0) break; Init (); for (int i=1;i<=m;i++) {scanf ("%d%d", &x,&y); Mp[x].push_back (y); } for (int i=1;i<=n;i++) {if (! Dfs[i]) Tarjan (i); } if (newflag==1) {printf ("yes\n"); } else printf ("no\n"); } return 0;}
(Tarjan algorithm) HDU 1269