Computer
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 4251 Accepted Submission(s): 2120
Problem Description
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.
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
51 12 13 11 1
Sample Output
32344
Author
scnu
Recommend
lcy | We have carefully selected several similar problems for you: 2242 1074 3899 2197 2195
一棵树求每个节点到叶子节点的最大距离,最后输出
ac代码
#include<stdio.h>#include<string.h>#include<queue>#include<string>#include<iostream>#define max(a,b) (a>b?a:b)using namespace std;int n,head[10010],cnt,vis[10010],s,maxn,dis[10010],d1[10010],d2[10010];struct s{ int u,v,w,next;}edge[20020];void add(int u,int v,int w){ edge[cnt].u=u; edge[cnt].v=v; edge[cnt].w=w; edge[cnt].next=head[u]; head[u]=cnt++;}void bfs(int u){ int i; queue<int>q; memset(vis,0,sizeof(vis)); vis[u]=1; dis[u]=0; s=u; maxn=1; q.push(u); while(!q.empty()) { int u=q.front(); q.pop(); for(i=head[u];i!=-1;i=edge[i].next) { int v=edge[i].v; if(!vis[v]) { vis[v]=1; dis[v]=dis[u]+edge[i].w; q.push(v); if(dis[v]>maxn) { maxn=dis[v]; s=v; } } } }}int main(){ //int n; while(scanf("%d",&n)!=EOF) { int i; cnt=0; memset(head,-1,sizeof(head)); for(i=2;i<=n;i++) { int v,w; scanf("%d%d",&v,&w); add(i,v,w); add(v,i,w); } bfs(1); bfs(s); for(i=1;i<=n;i++) { d1[i]=dis[i]; } bfs(s); for(i=1;i<=n;i++) { d2[i]=dis[i]; } for(i=1;i<=n;i++) { printf("%d\n",max(d1[i],d2[i])); } }}
版权声明:本文为博主原创文章,未经博主允许不得转载。