Computer
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 35047 Accepted Submission(s):
5633
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.
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<iostream> 2 #include<cstdio> 3 #include<string> 4 #include<cmath> 5 #include<cstring> 6 #include<queue> 7 #include<stack> 8 #include<algorithm> 9 #define maxn 10005 10 using namespace std; 11 12 struct edge 13 { 14 int next; 15 int to; 16 int dis; 17 }g[maxn<<1]; 18 19 inline int read() 20 { 21 char c=getchar(); 22 int res=0,x=1; 23 while(c<'0'||c>'9') 24 { 25 if(c=='-') 26 x=-1; 27 c=getchar(); 28 } 29 while(c>='0'&&c<='9') 30 { 31 res=res*10+(c-'0'); 32 c=getchar(); 33 } 34 return x*res; 35 } 36 37 int n,aa,bb,num,root,ans; 38 int last[maxn],d[maxn],dp[maxn],dp1[maxn]; 39 40 inline void add(int from,int to,int dis) 41 { 42 g[++num].next=last[from]; 43 g[num].to=to; 44 g[num].dis=dis; 45 last[from]=num; 46 } 47 48 void dfs(int x) 49 { 50 d[x]=1; 51 for(int i=last[x];i;i=g[i].next) 52 { 53 int v=g[i].to; 54 if(!d[v]) 55 { 56 dp[v]=dp[x]+g[i].dis; 57 dfs(v); 58 } 59 } 60 } 61 62 void dfs1(int x) 63 { 64 d[x]=1; 65 for(int i=last[x];i;i=g[i].next) 66 { 67 int v=g[i].to; 68 if(!d[v]) 69 { 70 dp[v]=dp[x]+g[i].dis; 71 dfs1(v); 72 } 73 } 74 } 75 76 void dfs2(int x) 77 { 78 d[x]=1; 79 for(int i=last[x];i;i=g[i].next) 80 { 81 int v=g[i].to; 82 if(!d[v]) 83 { 84 dp1[v]=dp1[x]+g[i].dis; 85 dfs2(v); 86 } 87 } 88 } 89 90 int main() 91 { 92 while(scanf("%d",&n)!=EOF) 93 { 94 ans=0;num=0; 95 memset(last,0,sizeof(last)); 96 memset(dp,0,sizeof(dp)); 97 memset(d,0,sizeof(d)); 98 memset(dp1,0,sizeof(dp1)); 99 for(int i=2;i<=n;i++) 100 { 101 aa=read();bb=read(); 102 add(i,aa,bb); 103 add(aa,i,bb); 104 } 105 dfs(1); 106 for(int i=1;i<=n;i++) 107 { 108 if(dp[i]>ans) 109 { 110 ans=dp[i]; 111 root=i; 112 } 113 } 114 memset(dp,0,sizeof(dp)); 115 memset(d,0,sizeof(d)); 116 dfs1(root); 117 ans=0; 118 memset(d,0,sizeof(d)); 119 for(int i=1;i<=n;i++) 120 { 121 if(dp[i]>ans) 122 { 123 ans=dp[i]; 124 root=i; 125 } 126 } 127 dfs2(root); 128 for(int i=1;i<=n;i++) 129 { 130 printf("%d ",max(dp[i],dp1[i])); 131 } 132 } 133 return 0; 134 }
Don't waste your time on a man/woman, who isn't willing to waste their time on you.
不要为那些不愿在你身上花费时间的人而浪费你的时间
--snowy
2019-01-18 07:49:19