算法1:两次BFS
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int n, u, v, w;
pair<int, long> bfs(vector<vector<pair<int, int>>>& g, int s) {
queue<pair<int, int>> q;
q.emplace(s, 0);
vector<int> seen(n + 1);
seen[s] = 1; // mark as seen
pair<int, long> ans{-1, 0};
while (not q.empty()) {
const auto [u, d] = q.front(); q.pop();
if (d > ans.second) ans.first = u, ans.second = d;
for (const auto& [v, w] : g[u]) {
if (seen[v]++) continue;
q.emplace(v, d + w);
}
}
return ans;
};
// debug helper function
void printGraph(vector<vector<pair<int, int>>>& g) {
for (int u = 1; u < g.size(); ++u) {
printf("%d's neighbours: [", u);
for (const auto& [v, w] : g[u])
printf("(%d, %d) ", v, w);
printf("]\n");
}
}
int main(void) {
scanf("%d", &n);
// build the undirected graph
vector<vector<pair<int, int>>> g(n + 1); // 1-Based
for (int i = 0; i < n - 1; ++i) {
scanf("%d %d %d", &u, &v, &w); // w == weight (权重)
g[u].emplace_back(v, w);
g[v].emplace_back(u, w);
}
// printGraph(g);
long dist = bfs(g, bfs(g, 1).first).second;
printf("%ld\n", dist * 10 + ((dist + 1) * dist >> 1));
}
TODO: 算法2:两次DFS