首页 > 代码库 > hdu 2196 Computer 树的直径
hdu 2196 Computer 树的直径
Computer
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
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
题意:给你一棵树,求每个点到树上的最远距离;
思路:根据树的直径原理,每个点的最远到为直径的某个端点;
#include<bits/stdc++.h>using namespace std;#define ll long long#define pi (4*atan(1.0))#define eps 1e-14const int N=2e5+10,M=1e6+10,inf=1e9+10;const ll INF=1e18+10,MOD=2147493647;struct is{ int v,w,nex;}edge[N];int head[N],edg;int dis[N];int deep,node1,node2;void init(){ memset(head,-1,sizeof(head)); memset(dis,0,sizeof(dis)); edg=0; deep=0;}void add(int u,int v,int w){ edg++; edge[edg].v=v; edge[edg].w=w; edge[edg].nex=head[u]; head[u]=edg;}void dfs(int u,int fa,int val,int &node){ dis[u]=max(dis[u],val); if(val>deep) { deep=val; node=u; } for(int i=head[u];i!=-1;i=edge[i].nex) { int v=edge[i].v; int w=edge[i].w; if(v==fa)continue; dfs(v,u,val+w,node); }}int main(){ int n; while(~scanf("%d",&n)) { init(); for(int i=2;i<=n;i++) { int v,w; scanf("%d%d",&v,&w); add(i,v,w); add(v,i,w); } dfs(1,-1,0,node1); deep=0; dfs(node1,-1,0,node2); deep=0; dfs(node2,-1,0,node1); for(int i=1;i<=n;i++) printf("%d\n",dis[i]); } return 0;}
hdu 2196 Computer 树的直径
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。