<center> computer </center>
<center> Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 37195 Accepted Submission(s): 6420 </center>
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 informatio,
<center>![]()
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. </center>
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
天天菜如狗,天天被吊打,我好惨一男的呀!今天训练赛遇到了这个本以为dp会在后面讲,结果发现这个就是而且还不是一般的DP,唉!真惨!
这个题看了许久还是不会后来还是CSDN了(woc还是csdn舒服CV大法也很吊),这个可以用树形DP或者树的直径这一性质去写,这里我就介绍下树的直径吧!
一棵树从任意一点出发走到距离它最远的一点,然后再从最远的出发走到距离它最远的一个点,那么这两个点就是这棵树的直径的两个端点,所以我们先用一个dfs跑出一个最远点,然后再用一个dfs从该点出发,跑出另一个端点,两个端点有了,而且在跑的过程中有一个动态数组记录每个节点的最远位置,(最远位置的终点一定为两个端点之一)第二次dfs跑的是距离一个端点最远距离,然后再用有个dfs从另一个端点出发跑,每次都取最远距离这样结果就是了(我去这不是还是用了dp),
这里再给一个大佬的博客讲的有用DP如何解!
#include<iostream>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<vector>
using namespace std;
typedef pair<int,int> pa;
int n,maxlen,s;
vector<pa>v[100100];
int dp[100100];
int dfs(int x,int y,int l)
{
if(maxlen<=l)//更新最新最长节点和 总长度的两端的值
{
maxlen=l;
s=x;
}
pa p;
for(int i=0;i<v[x].size() ;i++)// 进行dfs搜索
{
p=v[x][i];
if(p.first ==y) continue;// 如果该点的所连坐标和这次的反向就不进行查找
else
{
dfs(p.first ,x,l+p.second);
dp[p.first]=max(dp[p.first],l+p.second);// 更新节点的最长距离 去最长距离
}
}
}
int main()
{
while(cin>>n)
{
int x,y;
memset(dp,0,sizeof dp);//初始化
for(int i=0;i<=n;i++) v[i].clear();
for(int i=2;i<=n;i++)
{
cin>>x>>y;
v[x].push_back(make_pair(i,y));// v[]里面的值为 x ,<i,y> 表示为 x的下一个节点为 i 权值为 y;
v[i].push_back(make_pair(x,y));
}
s=0;
maxlen=0;
dfs(1,-1,0);//三个值分别是当前节点 给节点所连接的节点 到这个节点的最大值;
dfs(s,-1,0);// 三个dfs 分别找出两个最长的端点 最后一个dfs为更新节点;
dfs(s,-1,0);
for(int i=1;i<=n;i++) cout<<dp[i]<<endl;
}
return 0;
}