根据自己习惯写的dfs
这题需要知道树的直径
树的直径为树中最长的一条边
求树的直径的方法为 随机选取一个点x,在其他点中找到与这个点距离最远的一个点y
再在其他点中找到与y点距离最远的点
这时候与这个点的距离就为树的直径
只需要dfs两次就可以
注意恢复现场
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
const int M = 2 * N;
int n;
int h[N], e[M], w[M], ne[M], idx;
int dist[N];
int vis[N];
long long ans;
void add(int a, int b, int c) {
e[idx] = b;
w[idx] = c;
ne[idx] = h[a];
h[a] = idx++;
}
void dfs(int u, int distance) {
dist[u] = distance;
vis[u] = 1;
//cout << u << ' ' << distance << endl;
for (int i = h[u]; i != -1; i = ne[i]) {
int j = e[i];
if (!vis[j])
{
dfs(j, distance + w[i]);
vis[j] = 0;
}
}
}
int main()
{
cin >> n;
memset(h, -1, sizeof(h));
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, 0);
int u = 1;
for (int i = 2; i <= n; i++) {
if (dist[u] < dist[i])
u = i;
}
memset(vis, 0, sizeof(vis));
dfs(u, 0);
for (int i = 1; i <= n; i++) {
if (dist[u] < dist[i]) {
u = i;
}
}
ans = dist[u] * 10 + (long long)(dist[u] + 1) * dist[u] / 2;
cout << ans << endl;
return 0;
}