求树的直径解决

Computer

A school bought the first computer some time ago(so this computer’s id is 1). During the recent years the school bought N-1 new computers. Each new computer was connected to one of settled earlier. Managers of school are anxious about slow functioning of the net and want to know the maximum distance Si for which i-th computer needs to send signal (i.e. length of cable to the most distant computer). You need to provide this information.

Hint: the example input is corresponding to this graph. And from the graph, you can see that the computer 4 is farthest one from 1, so S1 = 3. Computer 4 and 5 are the farthest ones from 2, so S2 = 2. Computer 5 is the farthest one from 3, so S3 = 3. we also get S4 = 4, S5 = 4.
Input
Input file contains multiple test cases.In each case there is natural number N (N<=10000) in the first line, followed by (N-1) lines with descriptions of computers. i-th line contains two natural numbers - number of computer, to which i-th computer is connected and length of cable used for connection. Total length of cable does not exceed 10^9. Numbers in lines of input are separated by a space.
Output
For each case output N lines. i-th line must contain number Si for i-th computer (1<=i<=N).
Sample Input

1
2
3
4
5
5
1 1
2 1
3 1
1 1

Sample Output

1
2
3
4
5
3
2
3
4
4

题意:

求一颗树上每个点能到达的最远距离

题解:

先求树的直径,然后再直径两端点向每个点遍历,每个点取两者中较大的距离即为答案。

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <bits/stdc++.h>
using namespace std;
const int N=10010;
int head[N],pnt[N<<1],nxt[N<<1],wth[N<<1],E;
int dis[N],n,dep[N];
int S,T;
void add(int u,int v,int w) {
E++;pnt[E]=v;nxt[E]=head[u];wth[E]=w;head[u]=E;
}
void init() {
memset(head,0,sizeof head);E=0;
memset(dis,0,sizeof dis);
}
void dfs(int u,int f,int d) {
dep[u]=d;
for(int i=head[u];i;i=nxt[i]) {
int v=pnt[i];
if(v==f) continue;
dfs(v,u,d+wth[i]);
}
}
void dfs0(int u,int f,int d) {
dis[u]=max(dis[u],d);
for(int i=head[u];i;i=nxt[i]) {
int v=pnt[i];
if(v==f) continue;
dfs0(v,u,d+wth[i]);
}
}
int main() {
while(scanf("%d",&n)!=EOF) {
init();
for(int i=2;i<=n;i++) {
int x,y;
scanf("%d%d",&x,&y);
add(i,x,y);add(x,i,y);
}
dfs(1,0,0);
for(int i=1;i<=n;i++)
if(dep[S]<dep[i]) S=i;
dfs(S,0,0);
for(int i=1;i<=n;i++)
if(dep[T]<dep[i]) T=i;
dfs0(S,0,0);dfs0(T,0,0);
for(int i=1;i<=n;i++) {
printf("%d\n",dis[i]);
}
}
}