法一
模板
// O(n)
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 10010, M = 20010;
int n, u;
int q[N];
int dis[N];
int h[N], e[M], ne[M], w[M], idx;
void add (int a, int b, int c)
{
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx ++ ;
}
int bfs (int x)
{
memset(dis, -1, sizeof dis);
dis[x] = 0;
int hh = 0, tt = 0;
q[0] = x;
while(hh <= tt)
{
int t = q[hh ++ ];
for(int i = h[t] ; ~i ; i = ne[i])
{
int j = e[i];
if(dis[j] == -1)
{
dis[j] = dis[t] + w[i];
q[++ tt] = j;
}
}
}
if(x == 1)
{
int t = 1;
for(int i = 2 ; i <= n ; i ++ )
if(dis[i] > dis[t])
t = i;
return t;
}
if(x == u)
{
int mmax = 0;
for(int i = 1 ; i <= n ; i ++ ) mmax = max(mmax, dis[i]);
return mmax;
}
}
int main ()
{
cin >> n;
memset(h, -1, sizeof h);
for(int i = 0 ; i < n - 1 ; i ++ )
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c), add(b, a, c);
}
u = bfs(1);
if(u == 1) // 这样传上去的话答案会走第一个if语句
{
puts("0");
return 0;
}
cout << bfs(u) << endl;
return 0;
}
法二
树形dp
还未学待更新....