无边权(边权为1)
int n;
cin >> n;
vector<vector<int>> g(n+1);
vector<vector<int>> d(3, vector<int>(n+1));
for (int i=1; i<n; i++) {
int u, v;
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
int c = 0;
function<void(int,int,int)> dfs = [&](int u, int fa, int o) {
for (int v : g[u]) {
if (v == fa) continue;
d[o][v] = d[o][u] + 1;
if (d[o][v] > d[o][c]) c = v;
dfs(v, u, o);
}
};
dfs(1, 0, 0);
dfs(c, 0, 1);
dfs(c, 0, 2);
// cout << d << endl;
// d[2][c] 直径
vector<int> h; // 某条直径上的中心点,直径奇数一个,偶数两个
for (int i=1; i<=n; i++) {
if (d[1][i]+d[2][i] == d[2][c] && abs(d[1][i]-d[2][i]) == d[2][c]%2) h.push_back(i);
}
有边权
int n;
cin >> n;
vector<vector<pair<int,int>>> g(n+1);
vector<vector<int>> d(3, vector<int>(n+1));
for (int i=1; i<n; i++) {
int u, v, x;
cin >> u >> v >> x;
g[u].emplace_back(v, x);
g[v].emplace_back(u, x);
}
int c = 0;
function<void(int,int,int)> dfs = [&](int u, int fa, int o) {
for (auto [v, x] : g[u]) {
if (v == fa) continue;
d[o][v] = d[o][u] + x;
if (d[o][v] > d[o][c]) c = v;
dfs(v, u, o);
}
};
dfs(1, 0, 0);
dfs(c, 0, 1);
dfs(c, 0, 2);
// cout << d << endl;
// d[2][c] 直径