服务中心选址问题

服务中心选址问题

题目描述

服务中心的位置记为location,区域由[left,right]表示,服务中心到区域的距离为:

  1. 如果right < location,则距离为location - right
  2. 如果location < left,距离为left - location
  3. 如果left <= location <= right,则距离为0

输入:
第一行,一个整数N表示区域个数。
后面N行,每行两个整数,表示区域的左右起点终点。

输出:
一个整数,表示服务中心位置到所有区域的距离总和的最小值

题目分析

  1. 输入的区域包含交集
  2. 经过例子发现规律,距离之和最小的location在输入的所有区间left和right排序后的中间两个数组成的区间上。
  3. 例如:[1,2],[4,7],[5,20] 排序后为1,2,4,5,7,20,中间的两个数为4,5,则4<=location<=5时,距离最小;[1,3],[2,4],[4,5],[6,20],排序后1,2,3,4,4,5,6,20,中间两个数是4,4,则location=4,距离之和最小,为3

代码实现

size = int(input().strip())
rows = []
datas = []
for i in range(size):
    a, b = map(int, input().strip().split(' '))
    datas.append(a)
    datas.append(b)
    rows.append((a, b))
datas.sort()
i = len(datas) // 2 - 1
location = datas[i]
distance = 0
for start, end in rows:
    if location > end:
        distance += location - end
    elif location < start:
        distance += start - location

print(distance)

相关推荐

  1. 服务中心选址问题

    2024-03-11 16:36:04       19 阅读
  2. Nacos vs Eureka的区别:微服务注册中心选择

    2024-03-11 16:36:04       36 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-11 16:36:04       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-11 16:36:04       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-11 16:36:04       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-11 16:36:04       18 阅读

热门阅读

  1. C语言分支和循环语句—while

    2024-03-11 16:36:04       20 阅读
  2. PokéLLMon 源码解析(二)

    2024-03-11 16:36:04       21 阅读
  3. 解决Git中fatal: refusing to merge unrelated histories

    2024-03-11 16:36:04       24 阅读
  4. 【C/C++ 学习笔记】数组

    2024-03-11 16:36:04       25 阅读
  5. LeetCode:猜数字游戏

    2024-03-11 16:36:04       23 阅读
  6. LeetCode每日一题[C++]-猜数字游戏

    2024-03-11 16:36:04       23 阅读
  7. 基本工具学习--宝藏“课程”

    2024-03-11 16:36:04       18 阅读
  8. AcWing 1211. 蚂蚁感冒

    2024-03-11 16:36:04       22 阅读
  9. sora未来在哪里,是否改变世界

    2024-03-11 16:36:04       21 阅读
  10. 2024 年 AI 辅助研发趋势

    2024-03-11 16:36:04       20 阅读