树的直径
for (int i = 1; i < n; i++) {
int u, v;
cin >> u >> v;
edge[u].push_back(v);
edge[v].push_back(u);
}
auto bfs = [&](int s) {
std::queue<int> q;
std::vector<int> d(n, -1);
d[s] = 0;
q.push(s);
while (!q.empty()) {
int x = q.front();
q.pop();
for (auto it : edge[x]) {
if (d[it] == -1) {
d[it] = d[x] + 1;
q.push(it);
}
}
}
return d;
};
auto d0 = bfs(0);
int s = std::max_element(d0.begin(), d0.end()) - d0.begin();
auto ds = bfs(s);
int t = std::max_element(ds.begin(), ds.end()) - ds.begin();
auto dt = bfs(t);Last updated