先随机求离一个位置最远的点
再求离这个点最远的点即可
# include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
long long d[N], n, x, y, z, h, t, q[N], dmax, Mi;
bool st[N];
vector<int> s[N], sd[N];
int main()
{
cin >> n;
for(int i = 1; i < n; i ++)
{
cin >> x >> y >> z;
s[x].push_back(y);
s[y].push_back(x);
sd[x].push_back(z);
sd[y].push_back(z);
}
h = t = 0;
q[0] = 1;
d[1] = 0;
memset(st, false, sizeof st);
st[1] = true;
while(h <= t)
{
int out = q[h ++];
for(int i = 0; i < s[out].size(); i ++)
{
int ne = s[out][i];
if(!st[ne])
{
st[ne] = true;
d[ne] = d[out] + sd[out][i];
q[++t] = ne;
}
}
}
dmax = 0;
for(int i = 1; i <= n; i ++)
if(dmax < d[i]) dmax = d[i], Mi = i;
h = t = 0;
q[0] = Mi;
d[Mi] = 0;
memset(st, false, sizeof st);
st[Mi] = true;
while(h <= t)
{
int out = q[h ++];
for(int i = 0; i < s[out].size(); i ++)
{
int ne = s[out][i];
if(!st[ne])
{
st[ne] = true;
d[ne] = d[out] + sd[out][i];
q[++t] = ne;
}
}
}
dmax = 0;
for(int i = 1; i <= n; i ++) dmax = max(dmax, d[i]);
dmax = dmax * 10 + (1 + dmax) * dmax / 2;
cout << dmax;
}