Poj 2631 roads in the north (tree diameter)
Http://poj.org/problem? Id = 2631
Question:
There is a tree structure that gives you all the edges (u, v, cost) of the tree, indicating that there is a cost edge between u and v. then, what is the distance between the two Farthest Points on the tree? (That is, the diameter of the tree)
Analysis:
For the tree diameter problem, the <Introduction to algorithms> (22 2-7) examples are described.
Specific solution: First, starting from any vertex A on the tree, (BFS) finds the farthest vertex B. then, starting from point B (BFS), find the point C. the distance between BC is the diameter of the tree.
The program uses an adjacent table to represent the tree structure.
Head [I] = J indicates that the edge connected to the I node forms a linked list. The J edge is the first element of the chain, then, you can use J to find the remaining (connected to I) edge.
Edge indicates the structure of each edge.
BFS returns the number of the farthest point from the S Node
AC code: C ++ submit
// C ++ submit the statement # include <cstdio> # include <cstring> # include <algorithm> # include <queue> using namespace STD; const int maxn = 10000 + 5; const int maxm = 1000000 + 5; // side structure struct edge {edge () {} edge (int to, int cost, int next): To (), cost (cost), next (next) {} int to; int cost; int next;} edges [maxm]; // all edges int CNT; // total number of edges int head [maxn]; // header node // Add two directed edges void addedge (int u, int V, int cost) {edges [CNT] = edge (v, cost, head [u]); head [u] = Cn T ++; edges [CNT] = edge (u, cost, head [v]); head [v] = CNT ++ ;} // Dist [I] The distance from the current point of the table to I: int Dist [maxn]; // BFS returns the number of the farthest point that can be reached from the S node: int BFS (INT S) {int max_dist = 0; // records the longest distance int id = s; // records the farthest point queue <int> q; memset (Dist,-1, sizeof (DIST )); dist [s] = 0; q. push (s); While (! Q. empty () {int u = Q. front (); q. pop (); If (Dist [u]> max_dist) {max_dist = DIST [u]; id = u ;}for (INT I = head [u]; I! =-1; I = edges [I]. next) {edge & E = edges [I]; If (Dist [E. to] =-1) // you have not accessed E. to point {Dist [E. to] = DIST [u] + E. cost; q. push (E. to) ;}}} return ID;} int main () {int U, V, cost; memset (Head,-1, sizeof (head); CNT = 0; while (scanf ("% d", & U, & V, & cost) = 3) addedge (u, v, cost ); printf ("% d \ n", DIST [BFS (u)]); Return 0 ;}
Poj 2631 roads in the north (tree diameter)