Http://acm.hust.edu.cn: 8080/judge/problem/viewproblem. Action? Id = 24028
In fact, the principles of BFS and DFS are the same. They all find the deepest, but they both need to be done twice.
Find the deepest depth for the first time, and find the deepest depth for the second time
View code
# Include <iostream> # Include < String . H> # Include <Stdio. h> # Include <Algorithm> # Include <Vector> # Include <Queue> # Define INF ~ 0u> 1 # Define Maxn 100000 Using Namespace STD; Int N; vector < Int > Node [maxn]; pair < Int , Int > Ans; Int Visit [maxn]; Void Init (){ Int A, B; For ( Int I = 0 ; I <n; I ++ ) Node [I]. Clear (); For ( Int I = 1 ; I <n; I ++ ) {CIN > A> B; node [A]. push_back (B); node [B]. push_back ();}} Void BFS ( Int Root) {queue <Pair < Int , Int > Q; // Queue with two attributes Q. Push (make_pair (root, 0 )); // First, enter the root team Ans. Second = 0 ; Memset (visit, 0 , Sizeof (Visit); visit [root] = 1 ; While (! Q. Empty () {pair < Int , Int > Temp = Q. Front (); q. Pop (); If (Temp. Second> Ans. Second) {ans. Second = Temp. Second; ans. First = Temp. First ;} For ( Int I = 0 ; I <node [temp. First]. Size (); I ++ ) If (! Visit [node [temp. First] [I]) // No access to the team {Visit [node [temp. First] [I] = 1 ; Q. Push (make_pair (node [temp. First] [I], temp. Second + 1 ));}}} Int Main (){ Int Test; For (CIN> test; test -- ) {CIN > N; Init (); BFS ( 0 ); // For the first time, assume that 0 is the root of the BFS, and find the deepest point in depth. BFS (ANS. First ); // The second time, looking for the deepest point in Depth If (ANS. Second % 2 ) Cout <Ans. Second/ 2 +1 <Endl; // Half of the even answers plus 1 Else Cout <Ans. Second/ 2 <Endl; // Half of odd answers } Return 0 ;}