Want to see more problem-solving reports:Http://blog.csdn.net/wangjian8006/article/details/7870410
Reprinted please indicate the source:Http://blog.csdn.net/wangjian8006
There are n farms, and the N farms have some edge connections. Then you need to find two points to maximize the path length and output the maximum length.
Solution: because there is only one path, this figure is a tree. If we know a tree, we can find the maximum distance between two points. BFS can solve this problem twice.
First BFS: Search from any point and find the longest point from this point.
The second BFS: search from the point found by the first BFs, and find out the longest point in the BFS is the answer.
This is the same idea as poj1383.
/* Memory 1784 ktime 204 Ms */# include <queue> # include <iostream> using namespace STD; # define maxv 50000 # define MaxE 100000 typedef struct {int T, W, next;} edge; edge [MaxE]; int n, m; int e, head [maxv], record [maxv]; void addedge (int s, int t, int W) {edge [e]. T = T; edge [e]. W = W; edge [e]. next = head [s]; head [s] = e ++;} int BFS (int s, int flag) {int I, V, T; int TMP = 0, tmpi = s; queue <int> q; memset (record,-1, sizeof (record); record [s ] = 0; q. Push (s); While (! Q. Empty () {v = Q. Front (); q. Pop (); for (I = head [v]; I! =-1; I = edge [I]. next) {T = edge [I]. t; If (record [T] =-1) {record [T] = record [v] + edge [I]. w; If (record [T]> TMP) {TMP = record [T]; tmpi = T;} Q. push (t) ;}} return flag? Tmpi: TMP;} int main () {int A, B, W, ans; char C; while (~ Scanf ("% d \ n", & N, & M) {memset (Head,-1, sizeof (head); E = 0; while (M --) {scanf ("% d % C \ n", & A, & B, & W, & C); addedge (A, B, w); addedge (B, A, W);} A = BFS (1,1); ans = BFS (A, 0); printf ("% d \ n ", ans);} return 0 ;}