【问题描述:】 给定n个居民点的位置,求把邮局建在何处,可以使得所有居民点到邮局的距离总和最小。
【数据输入:】 第1行是居民点数n,1≤n≤10000。接下来n行是居民点的位置,每行2个整数x和y,-10000≤x,y≤10000。
【结果输出:】 1个数,是n个居民点到邮局的距离总和的最小值。
【输入示例】
5
1 2
2 2
1 3
3 -2
3 3
【输出示例】
10
- # 解题思路:邮局选址问题可以通过中位数策略来解决,通过找到所有居民点的中位数位置,我们可以最小化总距离。
-
- # 定义函数,接受居民点数量 n 和居民点位置列表 resident_locations 作为输入
-
-
- def optimal_post_office_location(n, resident_locations):
- # 分别提取 x 和 y 坐标
- x_coords = [location[0] for location in resident_locations]
- y_coords = [location[1] for location in resident_locations]
-
- # 对 x 和 y 坐标排序,以便找到中位数
- x_coords.sort()
- y_coords.sort()
-
- # 找到 x 和 y 坐标的中位数
- # 曼哈顿距离使得奇数和偶数的情况下都能得到确定的中位数
- median_x = x_coords[n // 2]
- median_y = y_coords[n // 2]
-
- # 计算每个居民点到中位数位置的距离,并将这些距离加起来,得到总距离
- total_distance = sum(abs(x - median_x) + abs(y - median_y)
- for x, y in resident_locations)
-
- # 返回总距离
- return total_distance
-
-
- # 输入数据,首先输入居民点数量 n
- n = int(input())
- resident_locations = [] # 初始化居民点位置列表
- # 循环输入每个居民点的位置,并将其添加到居民点位置列表中
- for _ in range(n):
- x, y = map(int, input().split())
- resident_locations.append((x, y))
-
- # 调用函数,计算并输出结果
- result = optimal_post_office_location(n, resident_locations)
- print(result) # 输出 10