1 // accepted 492 kb 0 MS 2 // tree diameter BFS 3 # include <cstdio> 4 # include <cstring> 5 # include <iostream> 6 # include <queue> 7 using namespace STD; 8 const int imax_n = 10005; 9 struct node10 {11 int U, V, C; 12 node () 13 {14 15} 16 node (int u, int V, int C): U (u), V (V), C (c) 17 {18 19} 20} p [2 * imax_n]; 21 int e; 22 int head [imax_n]; 23 int next [imax_n * 2]; 24 void addedge (int u, int V, int c) 25 {26 p [e] = node (u, v, c); 27 Next [e] = head [u]; 28 head [u] = e ++; 29} 30 void Init () 31 {32 memset (Head,-1, sizeof (head); 33 memset (next,-1, sizeof (next); 34 E = 0; 35} 36 bool vis [imax_n]; 37 int dis [imax_n]; 38 queue <int> q; 39 int BFS (INT s) 40 {41 int ans = 0; 42 int temp_node; 43 while (! Q. empty () Q. pop (); 44 memset (VIS, 0, sizeof (VIS); 45 Q. push (s); 46 vis [s] = 1; 47 memset (DIS, 0, sizeof (DIS); 48 While (! Q. empty () 49 {50 int x = Q. front (); 51 Q. pop (); 52 If (DIS [x]> ans) 53 {54 ans = dis [X]; 55 temp_node = X; 56} 57 for (INT I = head [X]; I + 1; I = next [I]) 58 {59 int y = P [I]. v; 60 if (! Vis [y]) 61 {62 vis [y] = 1; 63 Q. push (y); 64 if (DIS [x] + P [I]. c> dis [y]) 65 dis [y] = dis [x] + P [I]. c; 66} 67} 68} 69 return temp_node; 70} 71 int main () 72 {73 int X, Y, C; 74 Init (); 75 while (scanf ("% d", & X, & Y, & C )! = EOF) 76 // For (INT I = 0; I <5; I ++) 77 {78 // scanf ("% d", & X, & Y, & C); 79 addedge (X, Y, c); 80 addedge (Y, X, c); 81} 82 x = BFS (1 ); 83 y = BFS (x); 84 printf ("% d \ n", DIS [y]); 85 return 0; 86}View code
Poj2631 tree diameter + BFS