diff --git "a/01-\346\225\260\347\273\204/day04/problem_solving_05.py" "b/01-\346\225\260\347\273\204/day04/problem_solving_05.py" new file mode 100644 index 0000000000000000000000000000000000000000..715f0d9df65d6764b4b02c29ed9e06b113e471c9 --- /dev/null +++ "b/01-\346\225\260\347\273\204/day04/problem_solving_05.py" @@ -0,0 +1,50 @@ +""" +过桥的时间 +""" +import heapq +from typing import List + + +class Solution: + def findCrossingTime(self, n: int, k: int, time: List[List[int]]) -> int: + time.sort(key=lambda t: t[0] + t[2]) # 稳定排序 + cur = 0 + workL, waitL, waitR, workR = [], [[-i, 0] for i in range(k - 1, -1, -1)], [], [] # 下标越大效率越低 + while n: + while workL and workL[0][0] <= cur: + p = heapq.heappop(workL) + p[0], p[1] = p[1], p[0] + heapq.heappush(waitL, p) # 左边完成放箱 + while workR and workR[0][0] <= cur: + p = heapq.heappop(workR) + p[0], p[1] = p[1], p[0] + heapq.heappush(waitR, p) # 右边完成搬箱 + if waitR: # 右边过桥,注意加到 waitR 中的都是 <= cur 的(下同) + p = heapq.heappop(waitR) + cur += time[-p[0]][2] + p[1] = p[0] + p[0] = cur + time[-p[0]][3] + heapq.heappush(workL, p) # 放箱 + elif waitL: # 左边过桥 + p = heapq.heappop(waitL) + cur += time[-p[0]][0] + p[1] = p[0] + p[0] = cur + time[-p[0]][1] + heapq.heappush(workR, p) # 搬箱 + n -= 1 + elif len(workL) == 0: + cur = workR[0][0] # cur 过小,找个最小的放箱/搬箱完成时间来更新 cur + elif len(workR) == 0: + cur = workL[0][0] + else: + cur = min(workL[0][0], workR[0][0]) + while workR: + t, i = heapq.heappop(workR) # 右边完成搬箱 + # 如果没有排队,直接过桥;否则由于无论谁先过桥,最终完成时间都一样,所以也可以直接计算 + cur = max(t, cur) + time[-i][2] + return cur # 最后一个过桥的时间 + + +if __name__ == '__main__': + result = Solution().findCrossingTime(1, 3, [[1, 1, 2, 1], [1, 1, 3, 1], [1, 1, 4, 1]]) + print(result)