题面
题解
- 对于没有边权的树的直径的定义是路径上经过的边数最多
- 求解步骤 :1.任取一点作为起点,找到距离该点最远的一个点u(某一条直径的端点) 2.再找到距离u最远的一点v 3.那么u和v之间的路径就是一条直径 (BFS)
1.对于有边权的树,我们可以通过枚举来确定最长的直径
代码
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 2e4 + 10;
int n;
int h[N], e[N], w[N], ne[N], idx;
int ans;
void add(int a, int b, int c) {
e[idx] = b;
w[idx] = c;
ne[idx] = h[a];
h[a] = idx++;
}
int dfs(int u, int father) {
int dist = 0; //到u的最长距离
int d1 = 0, d2 = 0; //最长距离,次长距离
for (int i = h[u]; i != -1; i = ne[i]) {
int j = e[i];
if (j == father) continue; //不能向上走
int d = dfs(j, u) + w[i]; //儿子节点最长距离+这个儿子节点到u的距离
dist = max(dist, d);
if (d >= d1) d2 = d1, d1 = d;
else if (d > d2) d2 = d;
}
ans = max(ans, d1 + d2); //枚举最长直径
return dist;
}
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
memset(h, -1, sizeof h);
cin >> n;
for (int i = 1; i < n; i++) {
int a, b, c;
cin >> a >> b >> c;
add(a, b, c), add(b, a, c);
}
dfs(1, -1); //任选一点作为根节点开始遍历,不能向上走
cout << ans << endl;
return 0;
}