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.
- 最远距离等于反向最远与正向最远中的较大值取得。
- 正向最远由子节点正向最远加上到子节点的边权求得。
- 反向最远由父节点最远求得,其中可能是父节点正向最远,有可能是父节点反向最远。
- 父节点正向最远有可能通过正在确定答案的子节点,此时不应由这条正向最远更新答案。
- 4情况需要额外找一条正向次远来辅助确定答案。
#include <cstdio>
#include <cstring>
#define max(a, b) (a>b ? a:b)
#define min(a, b) (a<b ? a:b)
using namespace std;
const int N = 10101;
int dp[N][3], head[N], ver[N<<1], edge[N<<1], Next[N<<1], tot;
void init(){
memset(Next, 0, sizeof(Next));
memset(head, 0, sizeof(head));
tot = 1;
}
void add(int x, int y, int z){
ver[++tot] = y, edge[tot] = z, Next[tot] = head[x], head[x] = tot;
}
void dfs1(int x, int fa){
int big1 = 0, big2 = 0;
dp[x][1] = dp[x][0] = 0;
for(int i = head[x]; i; i = Next[i]){
int y = ver[i], z = edge[i];
if(y==fa) continue;
dfs1(y, x);
if(dp[y][0] + z > big1) big2 = big1, big1 = dp[y][0] + z;
else if(dp[y][0] + z > big2) big2 = dp[y][0] + z;
}
dp[x][0] = big1, dp[x][1] = big2;
}
void dfs2(int x, int fa){
for(int i = head[x]; i; i = Next[i]){
int y = ver[i], z = edge[i];
if(y == fa) continue;
//抖了个机灵大佬们不要喷我
dp[y][2] = max(dp[x][2], dp[x][dp[y][0]+z==dp[x][0]]) + z;
dfs2(y, x);
}
}
int main(){
int t;
while(~scanf("%d", &t)){
init();
for(int i = 2; i <= t; i++){
int x, y;
scanf("%d%d", &x, &y);
add(i, x, y);
add(x, i, y);
}
dfs1(1, 0);
dfs2(1, 0);
for(int i = 1; i <= t; i++){
printf("%d\n", max(dp[i][0], dp[i][2]));
}
}
return 0;
}
//%zx
//%lrh