算法1: 一次DFS
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define not !
#define and &&
#define or ||
#define r() fast_read()
#define rep(inc, frm, to) for (size_t inc = frm; inc < to; ++inc)
#define MAX_N 10010
typedef long long int ll;
ll fast_read(void) {
ll n = 0, sign = 1;
char c = getchar();
while (c < 48 or c > 57) {
if (c == '-') sign = ~0;
c = getchar();
}
while (c >= 48 and c <= 57) {
n = (n << 1) + (n << 3) + (c ^ 48);
c = getchar();
}
return sign * n;
}
// ==================== 图的链式前向星表示法 ====================
int head[MAX_N], edge_cnt;
typedef struct Edge Edge;
struct Edge {
int to, w, nxt;
} edges[MAX_N << 1];
void addEdge(int u, int v, int w) {
edges[++edge_cnt] = (Edge) {v, w, head[u]};
head[u] = edge_cnt;
}
void print_graph(const int n) {
rep(u, 1, n + 1) {
printf("Vertex: %ld --> ", u);
for (int e = *(head + u); e; e = edges[e].nxt)
printf("[%d, %d]\t", edges[e].to, edges[e].w);
putchar(10);
}
}
// ==================== 图的链式前向星表示法 ====================
int n, ans;
int DFS(int u, int p) {
int d1 = 0, d2 = 0; // d1最长路径长度, d2次长路径长度 (我认为说的不准确应该是边权和)
for (int e = *(head + u), to, w; e; e = edges[e].nxt) {
to = edges[e].to, w = edges[e].w;
if (to == p) continue;
int d = DFS(to, u) + w;
if (d > d1) d2 = d1, d1 = d;
else if (d > d2) d2 = d;
}
ans = fmax(ans, d1 + d2);
return d1;
}
signed main(int argc, char const *argv[]) {
// freopen("test.in", "r", stdin);
n = r();
int u, v, w;
rep(i, 0, n - 1) {
u = r(), v = r(), w = r();
addEdge(u, v, w), addEdge(v, u, w);
}
// print_graph(n);
DFS(1, 0);
printf("%d\n", ans);
// fclose(stdin);
return ~~(0 ^ 0);
}
算法2: 两次BFS
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int n, u, v, w;
pair<int, int> bfs(vector<vector<pair<int, int>>>& g, int start) {
queue<pair<int, int>> q;
q.emplace(start, 0);
vector<int> seen(n + 1);
seen[start] = 1;
int max_dist_node = -1, max_dist = -1;
while (not q.empty()) {
const auto [cur, dist] = q.front(); q.pop();
if (dist > max_dist) {
max_dist_node = cur;
max_dist = dist;
}
for (const auto& [nxt, d] : g[cur]) {
if (seen[nxt]) continue;
q.emplace(nxt, dist + d);
seen[nxt] = 1;
}
}
return {max_dist_node, max_dist};
};
int main(void) {
cin >> n;
vector<vector<pair<int, int>>> g(n + 1);
for (int i = 0; i < n - 1; ++i) {
cin >> u >> v >> w;
g[u].emplace_back(v, w);
g[v].emplace_back(u, w);
}
return printf("%d\n", bfs(g, bfs(g, 1).first).second), 0;
}