用 Python 编写程序检查我们是否可以接送给定列表中的每位乘客

pythonserver side programmingprogramming更新于 2026/2/4 17:48:17

假设我们有一个名为 requested_trips 的矩阵,其中每行包含 [start_x, end_x, num_passengers],并且还有一个容量值。现在,每个请求的行程都要求在 start_x 接送 num_passengers 名乘客,并在 end_x 送他们下车。我们还有一辆容量为给定值的汽车,从位置 x = 0 开始。我们想要接载每一位乘客,并且只能向右移动,我们必须检查我们是否可以接送每个人。

因此,如果输入为 trips = [[1, 25, 2], [3, 4, 3],[5, 12, 3]] capacity = 6,则输出将为 True

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

  • events := a new list

  • 对于 trips 中的每个集合 (sx, ex, np),执行

    • 在 events 末尾插入对 (sx, np)

    • 在事件

  • 携带 := 0

  • 对于事件列表(按排序顺序)中的每一对 (loc, delta),执行

    • 携带 := 携带 + delta

    • 如果携带 > 容量,则

      • 返回 False

  • 返回 True

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

示例

class Solution:
   def solve(self, trips, capacity):
      events = []
      for sx, ex, np in trips:
         events.append((sx, np))
         events.append((ex, -np))
      carrying = 0
      for loc, delta in sorted(events):
         carrying += delta
         if carrying > capacity:
            return False
      return True
ob = Solution()
trips = [
   [1, 25, 2],
   [3, 4, 3],
   [5, 12, 3]
]
capacity = 6
print(ob.solve(trips, capacity))

输入

trips = [
[1, 25, 2],
[3, 4, 3],
[5, 12, 3] ]
capacity = 6

输出

True

相关文章


有用资源