Time to live

Source: Internet
Author: User

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  ;} 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.