双十一期间,某著名电商平台“东东”为应对销售高峰,准备在n个城市中再增加一个自营仓库,其要求是该仓库设在n个城市中的某个城市,且距离其他所有城市的最短距离之和最小。请编写程序帮助“东东”找出设立仓库的地点。假定n个城市编号为0至n-1,它们之间至少有一个城市与其他所有城市可及。 输入格式: 输入包含多组数据。每组数据第一行为两个正整数n和e,均不超过100。n表示城市数。接下来e行表示两个城市间的距离信息,每行为3个非负整数a、b、c,其中a和b表示两个城市编号,c表示城市间的距离。 提示:可使用EOF判断输入结束。 输出格式: 输出为一个整数,表示建立仓库的城市编号,如多个城市满足要求,则输出编号最小者。
时间: 2023-12-03 22:42:57 浏览: 232
这是一个经典的最小生成树问题,可以使用 Prim 或者 Kruskal 算法来解决。
以下是使用 Prim 算法的 Python 代码实现:
```python
INF = float('inf')
while True:
try:
n, e = map(int, input().split())
edges = [[INF] * n for _ in range(n)]
for _ in range(e):
a, b, c = map(int, input().split())
edges[a][b] = edges[b][a] = c
# Prim algorithm
dist = [INF] * n
dist[0] = 0
visited = [False] * n
for _ in range(n):
# find the vertex with minimum distance
u = -1
for v in range(n):
if not visited[v] and (u == -1 or dist[v] < dist[u]):
u = v
visited[u] = True
# update distance
for v in range(n):
if not visited[v]:
dist[v] = min(dist[v], edges[u][v])
ans = 0
min_sum = INF
for i in range(n):
sum_dist = sum(edges[i])
if sum_dist < min_sum:
min_sum = sum_dist
ans = i
print(ans)
except EOFError:
break
```
首先读入城市数量和距离信息,然后使用邻接矩阵存储图的边权。接着使用 Prim 算法求出每个点到已选点集的最小距离,并在过程中顺便求出每个点到其他所有点的距离和。最后遍历所有城市,找出距离和最小的城市编号即可。
阅读全文
相关推荐
















