• 【python】邮局选址问题(中位数策略)


    题目:

    【问题描述:】 给定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

    代码:

    1. # 解题思路:邮局选址问题可以通过中位数策略来解决,通过找到所有居民点的中位数位置,我们可以最小化总距离。
    2. # 定义函数,接受居民点数量 n 和居民点位置列表 resident_locations 作为输入
    3. def optimal_post_office_location(n, resident_locations):
    4. # 分别提取 x 和 y 坐标
    5. x_coords = [location[0] for location in resident_locations]
    6. y_coords = [location[1] for location in resident_locations]
    7. # 对 x 和 y 坐标排序,以便找到中位数
    8. x_coords.sort()
    9. y_coords.sort()
    10. # 找到 x 和 y 坐标的中位数
    11. # 曼哈顿距离使得奇数和偶数的情况下都能得到确定的中位数
    12. median_x = x_coords[n // 2]
    13. median_y = y_coords[n // 2]
    14. # 计算每个居民点到中位数位置的距离,并将这些距离加起来,得到总距离
    15. total_distance = sum(abs(x - median_x) + abs(y - median_y)
    16. for x, y in resident_locations)
    17. # 返回总距离
    18. return total_distance
    19. # 输入数据,首先输入居民点数量 n
    20. n = int(input())
    21. resident_locations = [] # 初始化居民点位置列表
    22. # 循环输入每个居民点的位置,并将其添加到居民点位置列表中
    23. for _ in range(n):
    24. x, y = map(int, input().split())
    25. resident_locations.append((x, y))
    26. # 调用函数,计算并输出结果
    27. result = optimal_post_office_location(n, resident_locations)
    28. print(result) # 输出 10

  • 相关阅读:
    m基于matlab的OQPSK载波同步通信系统仿真,载波同步采用costas环
    【数据结构】—图的基本概念
    程序员对代码注释可以说是又爱又恨又双标
    在jar里限制指定的包名才可调用(白名单)。
    DNSlog漏洞探测
    聚观早报 | 遥感AI大模型发布;拼多多启动11.11大促
    Kubernetes是什么?以及基础功能介绍(基础之精通)1
    HBase Meta 元信息表修复实践
    C#的基本知识(1)
    代码注释有感
  • 原文地址:https://blog.csdn.net/fdxy12138/article/details/133944282