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.
46 lines
1.1 KiB
46 lines
1.1 KiB
#include <bits/stdc++.h>
|
|
using namespace std;
|
|
|
|
const int N = 10010, M = 20010;
|
|
// 暴力搜索,从每个节点为根出发,遍历整根树,找出距离自己的最大距离,然后每个最大距离取min
|
|
// 10/16,其它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++;
|
|
}
|
|
int st[N];
|
|
|
|
void dfs(int u, int sum) {
|
|
st[u] = 1;
|
|
if (sum > ans) ans = sum;
|
|
for (int i = h[u]; ~i; i = ne[i]) {
|
|
int j = e[i];
|
|
if (st[j]) continue; // 不走回头路
|
|
dfs(j, 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++) {
|
|
memset(st, 0, sizeof st);
|
|
dfs(i, 0);
|
|
}
|
|
|
|
// 输出结果
|
|
printf("%d", ans);
|
|
return 0;
|
|
} |