Week6 作业 A - Computer HDU - 2196
题目描述:
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.
思路:
与每一台电脑相距最远的电脑一定在端点处,也就是树的直径的两点,所以可以先求出这个树的两个直径端点,然后求这两个端点到某个电脑的距离,取最大的即可。
过程可以用3次dfs解决,第一次以任意一个点求端点v1,第二次以v1为原点求最大距离同时求出v2,第三次v2为原点进行dfs更新最大距离。
代码:
1 #include <cstdio> 2 #include <iostream> 3 #include <cstring> 4 using namespace std; 5 const int MAXN=1e5+5; 6 struct e 7 { 8 int v,w; 9 int next; 10 }Edge[MAXN]; 11 int last[MAXN]; 12 int visited[MAXN],dist[MAXN]; 13 int n,tot,vt,maxi; 14 15 void addEdge(int u,int v,int w) 16 { 17 tot++; 18 Edge[tot].v=v; 19 Edge[tot].w=w; 20 Edge[tot].next=last[u]; 21 last[u]=tot; 22 } 23 void dfs(int u,int dis) 24 { 25 visited[u]=1; 26 for(int i=last[u];i!=0;i=Edge[i].next) 27 { 28 int vv=Edge[i].v,ww=Edge[i].w; 29 if( !visited[vv] ) 30 { 31 if(dis+ww>dist[vv]) dist[vv]=dis+ww; 32 if(dis+ww>=maxi) 33 { 34 maxi=dis+ww; 35 vt=vv; 36 } 37 dfs(vv,dis+ww); 38 } 39 } 40 } 41 int main() 42 { 43 while( scanf("%d",&n)==1 ) 44 { 45 tot=0; maxi=0; vt=0; 46 memset(dist,0,sizeof(dist) ); 47 memset(visited,0,sizeof(visited)); 48 memset(last,0,sizeof(last)); 49 memset(Edge,0,sizeof(Edge) ); 50 for(int i=2;i<=n;i++) 51 { 52 int v,w; 53 scanf("%d %d",&v,&w); 54 addEdge(i,v,w); 55 addEdge(v,i,w); 56 } 57 //先找到两个端点v1,v2 58 int v1,v2; 59 dfs(1,0); v1=vt; 60 maxi=0; memset(visited,0,sizeof(visited)); 61 dfs(v1,0); v2=vt; 62 memset(visited,0,sizeof(visited)); 63 dfs(v2,0); 64 for(int i=1;i<=n;i++) 65 printf("%d\n",dist[i]); 66 } 67 68 return 0; 69 70 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步