树的直径
给定一棵树,树中每条边都有一个权值,树中两点之间的距离定义为连接两点的路径边权之和。树中最远的两个节点之间的距离被称为树的直径,连接这两点的路径被称为树的最长链。后者通常也可称为直径,即直径是一个 数值概念,也可代指一条路径
模板
题目
fter hearing about the epidemic of obesity in the USA, Farmer John wants his cows to get more exercise, so he has committed to create a bovine marathon for his cows to run. The marathon route will include a pair of farms and a path comprised of a sequence of roads between them. Since FJ wants the cows to get as much exercise as possible he wants to find the two farms on his map that are the farthest apart from each other (distance being measured in terms of total length of road on the path between the two farms). Help him determine the distances between this farthest pair of farms.
Input
Lines 1…: Same input format as “Navigation Nightmare”.
Output
Line 1: An integer giving the distance between the farthest pair of farms.
Sample Input
7 6
1 6 13 E
6 3 9 E
3 5 7 S
4 1 3 N
2 4 20 W
4 7 2 S
Sample Output
52
code:
#include <algorithm>
#include <cctype>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstring>
#include <deque>
#include <functional>
#include <list>
#include <map>
#include <iomanip>
#include <iostream>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
typedef long long ull;
const int maxn = 1e6 + 100;
inline int read() {
int s = 0, w = 1;
char ch = getchar();
while (!isdigit(ch)) { if (ch == '-') w = -1; ch = getchar(); }
while (isdigit(ch)) { s = (s << 1) + (s << 3) + (ch ^ 48); ch = getchar(); }
return s * w;
}
char ch;
int m, n;
struct Edge {
int next, to, dis;
}edge[maxn];
int num_edge = 0, ans = 0;
int head[maxn], vis[maxn], dis[maxn];
int point;
inline void add(int from, int to, int dis) {
edge[++num_edge].dis = dis;
edge[num_edge].to = to;
edge[num_edge].next = head[from];
head[from] = num_edge;
}
void bfs(int k) {
queue<int> q;
ans = 0;
memset(dis, 0, sizeof(dis));
memset(vis, 0, sizeof(vis));
while (!q.empty()) q.pop();
q.push(k); vis[k] = 1; point = k;
while (!q.empty()) {
int u = q.front(); q.pop();
for (int i = head[u]; i; i = edge[i].next) {
int v = edge[i].to;
if (!vis[v]) {
q.push(v);
dis[v] = dis[u] + edge[i].dis;
vis[v] = 1;
if (ans < dis[v]) {
ans = dis[v];
point = v;
}
}
}
}
}
int main() {
m = read(), n = read();
for (int i = 1; i <= n; ++i) {
int x, y, z;
x = read(), y = read(), z = read();
cin >> ch;
add(x, y, z);
add(y, x, z);
}
bfs(1), bfs(point);
printf("%d\n", ans);
return 0;
}