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