树的直径

本文详细解析了树的直径算法,介绍了如何通过两次广度优先搜索找到树中最长的路径,即树的直径。该算法首先从任意节点开始,找到离它最远的节点,再从这个节点出发,找到离它最远的节点,最后得到的路径即为树的直径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

树的直径

给定一棵树,树中每条边都有一个权值,树中两点之间的距离定义为连接两点的路径边权之和。树中最远的两个节点之间的距离被称为树的直径,连接这两点的路径被称为树的最长链。后者通常也可称为直径,即直径是一个 数值概念,也可代指一条路径

模板

题目

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值