You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
41 lines
1.0 KiB
41 lines
1.0 KiB
#include <bits/stdc++.h>
|
|
using namespace std;
|
|
|
|
const int N = 10010, M = N << 1;
|
|
// 暴力搜索,从每个节点为根出发,遍历整根树,找出距离自己的最大距离,然后每个最大距离取min
|
|
// 11/17,其它TLE,无法AC
|
|
int n;
|
|
int ans; // 树的直径
|
|
// 邻接表
|
|
int e[M], h[N], idx, w[M], ne[M];
|
|
void add(int a, int b, int c = 0) {
|
|
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
|
|
}
|
|
|
|
void dfs(int u, int fa, int sum) {
|
|
if (sum > ans) ans = sum;
|
|
for (int i = h[u]; ~i; i = ne[i]) {
|
|
int v = e[i];
|
|
if (v == fa) continue; // 不走回头路
|
|
dfs(v, u, sum + w[i]);
|
|
}
|
|
}
|
|
|
|
int main() {
|
|
// 初始化邻接表
|
|
memset(h, -1, sizeof h);
|
|
|
|
cin >> n;
|
|
for (int i = 1; i < n; i++) { // n-1条边
|
|
int a, b, c;
|
|
cin >> a >> b >> c;
|
|
add(a, b, c), add(b, a, c); // 无向图
|
|
}
|
|
|
|
// 多次dfs,是TLE的罪魁祸首
|
|
for (int i = 1; i <= n; i++) dfs(i, 0, 0);
|
|
|
|
// 输出结果
|
|
printf("%d", ans);
|
|
return 0;
|
|
} |