Computer
题目
Computer
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 37210 Accepted Submission(s): 6427
Problem Description
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.
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.
Output
For 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
求树的直径,不过有一点小思维,如果暴力求得话会超时,dis[i]存储的是i节点到起始节点的距离,我们先选择任意一个节点进行BFS 求得point为树的直径的一个端点,一次BFS即可求出。之后以point为起始点进行一次BFS dis1[i]表示i节点到point端点的距离,这次BFS后point的指向就是树的直径的另外一个端点。再以此端点进行一次BFS求得dis[i]为节点i到到此端点的距离,i的最长距离就是dis1[i]和dis[i]的最大值
代码奉上
#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
typedef long long ll;
typedef pair<ll,ll>P;
const ll maxn=12000;
ll ans;
ll point,point1;
bool vis[maxn];
ll dis[maxn];
ll dis1[maxn];
ll N;
vector<P>V[maxn];
void BFS(ll n)
{
memset(vis,0,sizeof(vis));
memset(dis,0,sizeof(dis));
dis[n]=0;
vis[n]=1;
queue<ll>Q;
Q.push(n);
while(!Q.empty())
{
ll jie;
jie=Q.front();
Q.pop();
for(ll i=0;i<V[jie].size();i++)
{
P jie1=V[jie][i];
if(!vis[jie1.first])
{
vis[jie1.first]=1;
dis[jie1.first]=dis[jie]+jie1.second;
if(dis[jie1.first]>ans)
{
ans=dis[jie1.first];
point=jie1.first;
}
Q.push(jie1.first);
}
}
}
}
int main()
{
int k=1;
while(~scanf("%lld",&N))
{
ll y,z,i,j;
for(i=2;i<=N;i++)
{
scanf("%lld%lld",&y,&z);
V[i].push_back(make_pair(y,z));
V[y].push_back(make_pair(i,z));
}
ans=0;
BFS(1);
point1=point;
ans=0;
BFS(point1);
for(i=1;i<=N;i++)
dis1[i]=dis[i];
ans=0;
BFS(point);
for(i=1;i<=N;i++)
{
ll Max=max(dis[i],dis1[i]);
printf("%lld\n",Max);
}
for(i=0;i<=N;i++)
V[i].clear();
}
return 0;
}