loj 1257 (求树上每一个点到树上另一个点的最长距离)

时间:2021-02-24 15:28:10

题目链接:http://lightoj.com/volume_showproblem.php?problem=1257

思路:首先需要用到一个知识点就是树上任一点到树上最长直径的某一个端点的距离最远,因此我们可以用dp[u]表示从u点出发到的最远距离,然后从任意一点出发,一遍dfs求出树上最长直径的某一个端点,然后从这个端点出发,再次dfs求出另一个端点,最后在从求出的端点出发进行dfs更新.每次做dfs时都更新一下dp.

 #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std; const int MAXN = ( + );
struct Edge {
int v, w, next;
}edge[MAXN << ];
int n, ans, NE, End, maxlen;
int head[MAXN]; void Insert(int u, int v, int w)
{
edge[NE].v = v;
edge[NE].w = w;
edge[NE].next = head[u];
head[u] = NE++;
} int dp[MAXN];
void dfs(int u, int father, int len)
{
if (len > maxlen) {
maxlen = len;
End = u;
}
for (int i = head[u]; i != -; i = edge[i].next) {
int v = edge[i].v;
int w = edge[i].w;
if (v == father) continue;
dfs(v, u, len + w);
dp[v] = max(dp[v], len + w);
}
} int main()
{
int _case, t = ;
scanf("%d", &_case);
while (_case--) {
scanf("%d", &n);
NE = ;
memset(head, -, sizeof(head));
for (int i = ; i < n; i++) {
int u, v, w;
scanf("%d %d %d", &u, &v, &w);
Insert(u, v, w);
Insert(v, u, w);
}
maxlen = ;
memset(dp, , sizeof(dp));
dfs(, -, );
dfs(End, -, );
dfs(End, -, );
printf("Case %d:\n", t++);
for (int i = ; i < n; i++) {
printf("%d\n", dp[i]);
}
}
return ;
}