HDU 1269 maze castle
Http://acm.hdu.edu.cn/showproblem.php? PID = 1, 1269
Problem description to train John's sense of direction, gardon built a big castle with N rooms (n <= 10000) and M channels (M <= 100000 ), each channel is one-way, that is, if a channel connects room A and Room B, it only means that the channel can be used to arrive at Room B from Room, but it does not indicate that it can be used to arrive at Room A from room B. Gardon needs to write Program Check whether any two rooms are connected, that is, for any I and j, there is at least one path from room I to room J, there is also a path from room J to room I.
The input contains multiple groups of data. The first row of the input has two numbers: N and M, and the next row of M has two numbers A and B, indicates that a channel can be used from Room A to room B. The file ends with two zeros.
For each group of input data, if any two rooms are connected to each other, output "yes"; otherwise, output "no ".
Sample input3 3 1 2 2 3 3 3 3 1 2 3 3 3 3 3 2 0 0
Sample outputyes No
Tarjan strong connectivity:
For strong connectivity problems, use TarjanAlgorithmIf you just make a judgment and check the set, you can also consider it! However, the role of the Tarjan algorithm is not only to determine whether to connect, but also to find the child trees!
# Include <iostream>
# Include <vector>
# Include <stack>
Using namespace STD;
# Deprecision Max 10001
Vector <int> V [Max];
Int dfn [Max], low [Max], index, count;
Bool instack [Max];
Stack <int> S;
Int min (int A, int B) {return a <B? A: B ;}
Void Tarjan (int u)
{
Dfn [u] = low [u] = ++ index;
Instack [u] = true;
S. Push (U );
Int I, K;
For (I = 0; I <V [u]. Size (); I ++)
{
K = V [u] [I];
If (! Dfn [k])
{
Tarjan (k );
Low [u] = min (low [u], low [k]);
}
Else if (instack [k])
Low [u] = min (low [u], dfn [k]);
}
If (low [u] = dfn [u])
{
Count ++;
Do
{
K = S. Top ();
S. Pop ();
Instack [k] = false;
}
While (u! = K );
}
}
Int na [Max], NB [Max];
Int main ()
{
Int n, m;
While (~ Scanf ("% d", & N, & M), N + M)
{
Int I, A, B;
For (I = 1; I <= N; I ++)
V [I]. Clear ();
Memset (Na, 0, sizeof (NA ));
Memset (Nb, 0, sizeof (NB ));
For (I = 1; I <= m; I ++)
{
Scanf ("% d", & A, & B );
V [A]. push_back (B );
}
Memset (dfn, 0, sizeof (dfn ));
Memset (instack, 0, sizeof (instack ));
Index = 0;
Int num = 0;
Count = 0;
For (I = 1; I <= N; I ++)
If (! Dfn [I])
Tarjan (I );
If (count> 1)
Puts ("no ");
Else
Puts ("yes ");
}
Return 0;
}