Computer
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 35047 Accepted Submission(s):
5633
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.
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.
number Si for i-th computer (1<=i<=N).
#include<iostream>
#include<cstdio>
#include<string>
#include<cmath>
#include<cstring>
#include<queue>
#include<stack>
#include<algorithm>
#define maxn 10005
using namespace std; struct edge
{
int next;
int to;
int dis;
}g[maxn<<]; inline int read()
{
char c=getchar();
int res=,x=;
while(c<''||c>'')
{
if(c=='-')
x=-;
c=getchar();
}
while(c>=''&&c<='')
{
res=res*+(c-'');
c=getchar();
}
return x*res;
} int n,aa,bb,num,root,ans;
int last[maxn],d[maxn],dp[maxn],dp1[maxn]; inline void add(int from,int to,int dis)
{
g[++num].next=last[from];
g[num].to=to;
g[num].dis=dis;
last[from]=num;
} void dfs(int x)
{
d[x]=;
for(int i=last[x];i;i=g[i].next)
{
int v=g[i].to;
if(!d[v])
{
dp[v]=dp[x]+g[i].dis;
dfs(v);
}
}
} void dfs1(int x)
{
d[x]=;
for(int i=last[x];i;i=g[i].next)
{
int v=g[i].to;
if(!d[v])
{
dp[v]=dp[x]+g[i].dis;
dfs1(v);
}
}
} void dfs2(int x)
{
d[x]=;
for(int i=last[x];i;i=g[i].next)
{
int v=g[i].to;
if(!d[v])
{
dp1[v]=dp1[x]+g[i].dis;
dfs2(v);
}
}
} int main()
{
while(scanf("%d",&n)!=EOF)
{
ans=;num=;
memset(last,,sizeof(last));
memset(dp,,sizeof(dp));
memset(d,,sizeof(d));
memset(dp1,,sizeof(dp1));
for(int i=;i<=n;i++)
{
aa=read();bb=read();
add(i,aa,bb);
add(aa,i,bb);
}
dfs();
for(int i=;i<=n;i++)
{
if(dp[i]>ans)
{
ans=dp[i];
root=i;
}
}
memset(dp,,sizeof(dp));
memset(d,,sizeof(d));
dfs1(root);
ans=;
memset(d,,sizeof(d));
for(int i=;i<=n;i++)
{
if(dp[i]>ans)
{
ans=dp[i];
root=i;
}
}
dfs2(root);
for(int i=;i<=n;i++)
{
printf("%d\n",max(dp[i],dp1[i]));
}
}
return ;
}
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