求一棵树的直径的方法就是,从一个顶点出发,找到离它最远的顶点s,然后从顶点s出发,找离他最远的节点t.那么,s、t之间的距离就是树的直径。
对于加权无向树来说,树的直径就是s、t之间的路径上的边的权值相加。
题目:GRL_5_A
AC代码:
#include <iostream>
#include <vector>
#include <queue>
#include <string.h>
#include <algorithm>
using namespace std;
#define MAXN 100005
struct edge
{
int from, to, weight;
};
vector<edge> vec[MAXN];
int n;
bool cmp(const int &a, const int &b)
{
return a > b;
}
int d[MAXN];
void bfs(int r)
{
queue<int> q;
bool vis[MAXN] = {false};
q.push(r);
vis[r] = true;
memset(d, 0, sizeof(d));
while (!q.empty())
{
int u = q.front();
q.pop();
for (edge e : vec[u])
{
if (!vis[e.to])
{
d[e.to] = d[u] + e.weight;
q.push(e.to);
vis[e.to] = true;
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
int s, t, w;
edge tmp1, tmp2;
for (int i = 0; i < n - 1; ++i)
{
cin >> s >> t >> w;
tmp1.from = s;
tmp1.to = t;
tmp1.weight = tmp2.weight = w;
tmp2.from = t;
tmp2.to = s;
vec[s].push_back(tmp1);
vec[t].push_back(tmp2);
}
bfs(0);
int m = -1, v;
for (int i = 0; i < n; ++i)
if (d[i] > m)
{
m = d[i];
v = i;
}
bfs(v);
sort(d, d + n, cmp);
cout << d[0] << endl;
}
转载请注明出处:https://www.longjin666.top/?p=767
欢迎关注我的公众号“灯珑”,让我们一起了解更多的事物~