![](https://i-blog.csdnimg.cn/blog_migrate/7ae21b9e0761007801add0cebc7f6325.png)
![](https://i-blog.csdnimg.cn/blog_migrate/73a6c5221e2709e0e40ba8604c653e1a.png)
样例输入:
5
1 2 2
1 3 1
2 4 5
2 5 4
样例输出:
135
求树的直径:
1.在树中随便找一个点x
2.求出距离点x的最远距离点y
3.求出距离点y最远的距离即是树的直径
算法:dfs
时间复杂度:O(N)
#include<iostream>
#include<cstring>
using namespace std;
typedef long long LL;
const int N = 1e5 + 10, M = 2 * N;
int h[N], ne[M], e[M], w[M], idx;
int n;
int dis[N];
void add(int a, int b, int v)
{
e[idx] = b;
w[idx] = v;
ne[idx] = h[a];
h[a] = idx++;
}
void dfs(int u, int father, int v)
{
dis[u] = v;
for (int i = h[u]; ~i; i = ne[i]) {
int j = e[i];
if (j != father) {
dfs(j, u, w[i] + v);
}
}
}
int main()
{
cin >> n;
memset(h, -1, sizeof(h));
for (int i = 0; i < n - 1; i++) {
int a, b, w;
cin >> a >> b >> w;
add(a, b, w);
add(b, a, w);
}
dfs(1, -1, 0);
int t = 1;
for (int i = 1; i <= n; i++) {
if (dis[i] > dis[t]) {
t = i;
}
}
dfs(t, -1, 0);
for (int i = 1; i <= n; i++) {
if (dis[i] > dis[t]) {
t = i;
}
}
LL s = dis[t];
LL ans = 10 * s + s * (s + 1) / 2;
cout << ans << endl;
return 0;
}