Find the diameter of a tree. The question does not contain the data range. In any case, it is obviously O (n.
DFS is used here. First, find the farthest point of any point, and then find the farthest point from this farthest point. The last two points are the answer.
View code
1 program pku1985(input,output);
2 type
3 node = ^link;
4 link = record
5 goal,w : longint;
6 next : node;
7 end;
8 var
9 l : array[0..50000] of node;
10 d : array[0..50000] of longint;
11 v : array[0..50000] of boolean;
12 n,m : longint;
13 procedure add(xx,yy,ww :longint );
14 var
15 tt : node;
16 begin
17 new(tt);
18 tt^.next:=l[xx];
19 tt^.goal:=yy;
20 tt^.w:=ww;
21 l[xx]:=tt;
22 end; { add }
23 procedure init;
24 var
25 i,xxx,yyy,www : longint;
26 begin
27 readln(n,m);
28 for i:=1 to n do
29 l[i]:=nil;
30 for i:=1 to m do
31 begin
32 readln(xxx,yyy,www);
33 add(xxx,yyy,www);
34 add(yyy,xxx,www);
35 end;
36 end; { init }
37 procedure dfs(now,dist : longint );
38 var
39 t : node;
40 begin
41 d[now]:=dist;
42 t:=l[now];
43 while t<>nil do
44 begin
45 if not v[t^.goal] then
46 begin
47 v[t^.goal]:=true;
48 dfs(t^.goal,dist+t^.w);
49 end;
50 t:=t^.next;
51 end;
52 end; { dfs }
53 procedure main;
54 var
55 i,maxn,maxl : longint;
56 begin
57 fillchar(d,sizeof(d),0);
58 fillchar(v,sizeof(v),false);
59 v[1]:=true;
60 dfs(1,0);
61 maxl:=0;
62 for i:=1 to n do
63 if d[i]>maxl then
64 begin
65 maxl:=d[i];
66 maxn:=i;
67 end;
68 fillchar(d,sizeof(d),0);
69 fillchar(v,sizeof(v),false);
70 v[maxn]:=true;
71 dfs(maxn,0);
72 maxl:=0;
73 for i:=1 to n do
74 if d[i]>maxl then
75 maxl:=d[i];
76 writeln(maxl);
77 end; { main }
78 begin
79 init;
80 main;
81 end.