题意:对于一棵给定的最小生成树,当以树中的任一结点作为根节点时,求此时的最长分支
分析:比较任意节点到组成此树直径的两端点的距离大小即可
Input:
5
1 1
2 1
3 1
1 1
Output:
3
2
3
4
4
//Time 31ms //Memory 1976k //Date 2015.03.30 #include <cstdio> #include <cstring> #include <algorithm> using namespace std; class Edge{ public: int v; int w; int nextE; }; const int MAX=10001; int n; Edge edges[20000]; int head[MAX],d1[MAX],d2[MAX]; int x; void DFS(int r,int f,int *d){ int e,v; for(e=head[r];e!=-1;e=edges[e].nextE){ v=edges[e].v; if(v!=f){ d[v]=d[r]+edges[e].w; if(d[x]<d[v]) x=v; DFS(v,r,d); } } } int main(){ int i,u,v,w,e; while(scanf("%d",&n)!=EOF){ e=0; memset(head,-1,sizeof(head)); for(u=2;u<=n;u++){ scanf("%d%d",&v,&w); edges[e].v=v;edges[e].w=w; edges[e].nextE=head[u]; head[u]=e++; edges[e].v=u;edges[e].w=w; edges[e].nextE=head[v]; head[v]=e++; } d1[1]=0;x=1; DFS(1,0,d1); d1[x]=0; DFS(x,0,d1); d2[x]=0; DFS(x,0,d2); for(i=1;i<=n;i++) printf("%d\n",max(d1[i],d2[i])); } return 0; }