Computer
Problem descriptiona 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.
Inputinput 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.
Outputfor each case output n lines. I-th line must contain number si for I-th computer (1 <= I <= N ).
Sample Input
51 12 13 11 1
Sample output
32344
Authorscnu
Recommendlcy | we have carefully selected several similar problems for you: 1561 1011 3456 1520
Question:
Tell you how far a tree can reach a certain point?
Solution:
Start from and find the distance from each point to. The farthest point must be one of the main branches of the tree.
Starting from the point on the trunk of the tree, the farthest point must be another point on the trunk of the tree.
The next answer is to increase the distance between each point and two main points.
Solution code:
#include <iostream>#include <cstdio>#include <climits>#include <map>#include <vector>#include <algorithm>using namespace std;const int maxn=11000;struct edge{ int u,v,w; int next; edge(int u0=0,int v0=0,int w0=0){ u=u0;v=v0;w=w0;}}e[maxn*2];int n,cnt,head[maxn],d[maxn],dx[maxn],dy[maxn];void initial(){ cnt=0; for(int i=0;i<=n;i++) head[i]=-1;}void addedge(int u,int v,int w){ e[cnt]=edge(u,v,w);e[cnt].next=head[u];head[u]=cnt++;}void input(){ int x,y,w0; for(int i=2;i<=n;i++){ scanf("%d%d",&y,&w0); addedge(i,y,w0); addedge(y,i,w0); }}void dfs(int u,int fa,int dis,int *d){ for(int i=head[u];i!=-1;i=e[i].next){ int v=e[i].v,w=e[i].w; if(v!=fa) dfs(v,u,d[v]=dis+w,d); }}void solve(){ int x=1,y=1; dfs(1,-1,d[1]=0,d); for(int i=1;i<=n;i++) if(d[x]<d[i]) x=i; dfs(x,-1,dx[x]=0,dx); for(int i=1;i<=n;i++) if(dx[y]<dx[i]) y=i; dfs(y,-1,dy[y]=0,dy); for(int i=1;i<=n;i++) d[i]=max(dx[i],dy[i]); for(int i=1;i<=n;i++) printf("%d\n",d[i]);}int main(){ while(scanf("%d",&n)!=EOF){ initial(); input(); solve(); } return 0;}