Hihocoder (1050) The longest path in the tree

Source: Internet
Author: User

The longest path of the tree, that is, to find a tree diameter problem, DFS and BFS can be resolved, but always feel that the DFS comparison around, not good understanding.

Then wrote the method of BFS, wherein 0 nodes as Sentinel, each time from the queue to remove 0 nodes, we know that a round of BFS end, you can add a depth.

The idea of BFS is simple:

1. Randomly find a node, with the node as the starting point for the BFS, the last vertex, must be one end of the diameter.

2. Once the BFS is started at one end of the diameter, the other end of the diameter is drawn, and the diameter (the longest path) is then between the two ends.

At first it was always WA, and then I found out that I had forgotten to clear the vertex marks.

1#include <cstdio>2#include <cstring>3#include <iostream>4#include <vector>5#include <queue>6 7 using namespacestd;8 9vector<int> tree[100010];Ten BOOLused[100010]; One intN; A intans; -  - intBFsintnum) the { -Ans =0; -memset (Used,0,sizeof(used)); -     intPoint ; +queue<int>Q;  - Q.push (num); +Q.push (0); A      while(!Q.empty ()) { at         intp =Q.front (); - Q.pop (); -  -         if(p = =0&&!Q.empty ()) { -ans++; -Q.push (0);  in             Continue; -         } to         Else if(p==0) { +              Break; -         } the  *          for(size_t i =0; I < tree[p].size (); ++i) { $             if(!Used[tree[p][i]]) {Panax Notoginseng Q.push (Tree[p][i]); -Used[tree[p][i]] =true; the             } +         } A  thePoint =p; +     } -  $     returnPoint ; $ } -  - intMain () the { -     intu,v;Wuyiscanf"%d", &N); the      for(inti =1; i < N; ++i) { -scanf"%d%d", &u, &v); Wu Tree[u].push_back (v); - tree[v].push_back (u); About     } $BFS (BFS (1)); -printf"%d\n", ans); -     return 0; -}
View Code

Hihocoder (1050) The longest path in the tree

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.