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.
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.InputInput 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.OutputFor each case output N lines. i-th line must contain number Si for i-th computer (1<=i<=N).Sample Input
5 1 1 2 1 3 1 1 1
Sample Output
3 2 3 4 4
题解:直接对每个点进行搜索的话肯定会超时,这里涉及到树的直径问题,记直径的一段为a,另一端记为b。那么树中任意一点所能走到的最长距离就是max(到a的距离,到b的距离).剩下的就是在求直径的过程中求每个点到根(既端点)的距离
1 #include<vector> 2 #include<cstdio> 3 #include<cstring> 4 #include<iostream> 5 #include<algorithm> 6 using namespace std; 7 8 const int maxn=1e5+5; 9 10 struct node{ 11 int to,next,va; 12 }e[maxn]; 13 14 int n,tot; 15 int head[maxn],d1[maxn],d2[maxn]; 16 17 void Inite(){ 18 tot=0; 19 memset(head,-1,sizeof(head)); 20 } 21 22 void addedge(int u,int v,int w){ 23 e[tot].to=v; 24 e[tot].va=w; 25 e[tot].next=head[u]; 26 head[u]=tot++; 27 } 28 29 void DFS(int pa,int u,int d[]){ 30 for(int i=head[u];i!=-1;i=e[i].next){ 31 int v=e[i].to; 32 if(pa==v) continue; 33 d[v]=d[u]+e[i].va; 34 DFS(u,v,d); 35 } 36 } 37 38 int main() 39 { while(~scanf("%d",&n)){ 40 Inite(); 41 for(int i=2;i<=n;i++){ 42 int u,va; 43 scanf("%d%d",&u,&va); 44 addedge(i,u,va); 45 addedge(u,i,va); 46 } 47 memset(d1,0,sizeof(d1)); 48 DFS(0,1,d1); 49 50 int temp=0; 51 for(int i=1;i<=n;i++) if(d1[temp]<d1[i]) temp=i; 52 53 memset(d1,0,sizeof(d1)); 54 DFS(0,temp,d1); 55 56 temp=0; 57 for(int i=1;i<=n;i++) if(d1[temp]<d1[i]) temp=i; 58 59 memset(d2,0,sizeof(d2)); 60 DFS(0,temp,d2); 61 62 for(int i=1;i<=n;i++) cout<<max(d1[i],d2[i])<<endl; 63 } 64 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 智能桌面机器人:用.NET IoT库控制舵机并多方法播放表情
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 新年开篇:在本地部署DeepSeek大模型实现联网增强的AI应用
· DeepSeek火爆全网,官网宕机?本地部署一个随便玩「LLM探索」
· Janus Pro:DeepSeek 开源革新,多模态 AI 的未来
· 上周热点回顾(1.20-1.26)
· 【译】.NET 升级助手现在支持升级到集中式包管理