[NOIpTG2007]树网的核——[floyd]

本文介绍了一种在树结构中寻找特定路径的算法,目标是在不超过最大长度限制的前提下,找到一条路径,使得树中所有其他节点到该路径的最大距离最小。通过Floyd算法计算节点间距离,并枚举树的直径上的路径来解决问题。

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

在这里插入图片描述
在这里插入图片描述
【题意分析】

把题目从ccf语转化成中文:在树的直径上取一段路径,使得所有其他节点到这条路径的最大距离最小,而且取的这段路径长度不能超过maxlen

数据规模300小得可怕,所以直接上n^3算法。

直接floyd求出两两之间距离,然后可以由两两之间最大距离得到树的直径即两端节点

然后枚举直径上的路径,直接暴力找出答案,取一个min⁡\minmin

Code:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <algorithm>
#define rep(i,a,b) for (register int (i) = (a); (i) <= (b); (i)++)
#define MAXN 1050
#define INF 999999999
using namespace std;

int dist[MAXN][MAXN], Dl[MAXN], Dr[MAXN], tot, n, maxlen, d, ans = INF;

inline int read () {
	register int s = 0, w = 1;
	register char ch = getchar ();
	while (! isdigit (ch)) {if (ch == '-') w = -1; ch = getchar ();}
	while (isdigit (ch)) {s = (s << 3) + (s << 1) + (ch ^ 48); ch = getchar ();}
	return s * w;
}

int main () {
	n = read (), maxlen = read ();
	rep (i, 0, MAXN) rep (j, 0, MAXN) dist[i][j] = i == j ? 0 : INF;
	rep (i, 1, n - 1) {
		int u = read (), v = read (), w = read ();
		dist[u][v] = dist[v][u] = w;
	}
	rep (k, 1, n) rep (i, 1, n) rep (j, 1, n) dist[i][j] = min (dist[i][j], dist[i][k] + dist[k][j]);
	rep (i, 1, n) rep (j, 1, n) if (dist[i][j] != INF) d = max (d, dist[i][j]);
	rep (i, 1, n) rep (j, 1, n) if (dist[i][j] == d) Dl[++tot] = i, Dr[tot] = j;
	rep (i, 1, n) rep (j, 1, n) {
		int res = 0;
		rep (k, 1, tot)
			if (dist[Dl[k]][i] + dist[i][j] + dist[j][Dr[k]] == d && dist[i][j] <= maxlen && dist[i][j] != INF) {
				rep (l, 1, n) if (l != i && l != j)
					res = max (res, (dist[l][i] + dist[l][j] - dist[i][j]) / 2);
				ans = min (ans, res);
			}
	}
	return printf ("%d\n", ans), 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值