杭电2196Computer(求每个点的最长路)

来源:互联网 发布:python网络数据采集pdf 编辑:程序博客网 时间:2024/05/14 15:06
 Computer
Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u
Submit Status

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.

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

3234

4

求每个点的最长路

#include<stdio.h>#include<string.h>#include<queue>#include<algorithm>const int MAX=10000+10;const int MAXN=10000*2+10;using namespace std;struct Edge{int from,to,val,next;}edge[MAXN];int dist[MAX];int vis[MAX];int head[MAX];int top;void init(){top=0;memset(head,-1,sizeof(head));}void addedge(int u,int v,int w){Edge E={u,v,w,head[u]};edge[top]=E;head[u]=top++;}int bfs(int sx){queue<int>q;memset(dist,0,sizeof(dist));memset(vis,0,sizeof(vis));int node=sx;int ans=0;vis[sx]=1;q.push(sx);while(!q.empty()){int u=q.front();q.pop();for(int i=head[u];i!=-1;i=edge[i].next){Edge E=edge[i];if(!vis[E.to]){dist[E.to]=dist[u]+E.val;if(ans<dist[E.to]){ans=dist[E.to];    node=E.to;}vis[E.to]=1;q.push(E.to);}}}return node;}int main(){int n,a,b;int d1[MAX],d2[MAX];int S,T;while(~scanf("%d",&n)){init();     for(int i=2;i<=n;i++)  {scanf("%d%d",&a,&b);addedge(i,a,b);addedge(a,i,b); } int S=bfs(1); int T=bfs(S); for(int i=1;i<=n;i++) d1[i]=dist[i]; bfs(T); for(int i=1;i<=n;i++) d2[i]=dist[i]; for(int i=1;i<=n;i++) printf("%d\n",d1[i]>d2[i]?d1[i]:d2[i]);}return 0;}

0 0
原创粉丝点击