首页 文章资讯内容详情

使用Python查找任何城市与车站之间的最大距离

2026-06-05 1 花语

假设我们有N个城市,并且它们的编号从0到N-1,并且我们也有车站所在的城市,我们必须找出任何城市与其最近车站之间的最大距离。我们必须记住,带车站的城市可以任意顺序给出。

因此,如果输入为N=6且测站=[2,4],则输出将为2

为了解决这个问题,我们将遵循以下步骤-

station_present:=大小为N的列表,并用False填充

对于车站中的每个城市,

station_present[city]:=True

dist:=0,maximum_dist:=最小电台

对于0到N范围内的城市,请执行

距离:=距离+1

maximum_dist:=(dist+1)的最大值/2,max_dist

dist:=0

如果station_present[city]为True,则

除此以外,

返回max_dist的最大值,dist

范例(Python)

让我们看下面的实现以更好地理解-

def get_max_dist(N, station): station_present = [False] * N for city in station: station_present[city] = True dist, maximum_dist = 0, min(station) for city in range(N): if station_present[city] == True: maximum_dist = max((dist + 1) // 2, maximum_dist) dist = 0 else: dist += 1 return max(maximum_dist, dist) N = 6 station = [2, 4] print(get_max_dist(N, station))

输入值

6, [2,4]

输出结果

2