Pra*_*wal 5 java arrays algorithm dynamic-programming data-structures
我陷入了一个问题。我知道dp可以在这里应用,但没有得到它。
0考虑从 开始并结束于 的正数轴的一部分10^9。您从 开始0,有 N 个任务可以执行。
该ith任务已完成l[i]并且需要t[i]时间来执行。要执行ith任务,您必须到达该地点l[i]并t[i]在该地点花费时间。
在路径上行进一个单位需要一秒钟,即从 1 到 3 需要 (3 - 1) = 2 秒。
你有 T 秒的时间,在这段时间里你必须执行尽可能多的任务并返回到起始位置。我需要找到可以在时间 T 内执行的最大值。
例子
考虑 M = 3、T = 10、l[] = [1, 2] 和 t[] = [3, 2]。
如果我们执行第一个任务,则消耗的总时间为 1(旅行)+ 3(完成任务)= 4。剩余时间为 10 - 4 = 6。
现在,如果我们连续执行第二个任务,则所需的总时间为 1(从 1 出发)+ 2(完成任务)= 3。剩余时间为 6 - 3 = 3。
现在如果我们从2返回到0。总共花费的时间是2。剩余时间是3 - 2 = 1。因此我们可以在给定的时间内安全地完成这两个任务。所以答案是2。
限制很高:
1 <= N <= 10 ^ 5
0 <= T <= 10 ^ 8
0 <= l[i], t[i] <= 10 ^ 9
Run Code Online (Sandbox Code Playgroud)
有一个最佳解决方案,我们从 0 到某个坐标 x 并返回,贪婪地选择区间 [0, x] 中从最短到最长的任务。
可能有一个动态编程解决方案,但这不是我首先要达到的。相反,我会使用扫描线算法将 x 从 0 增加到 T/2,从而保持最佳解决方案。当 x 通过时l[i],我们将任务添加i到议程中。每当当前议程占用太多时间时,我们就会放弃最长的任务。
该算法在 Python 中看起来像这样(未经测试)。
import heapq
def max_tasks(T, l, t):
x = 0
heap = []
opt = 0
# Sweep the tasks left to right
for l_i, t_i in sorted(zip(l, t)):
# Increase x to l_i
T -= 2 * (l_i - x)
x = l_i
# Add task i to the agenda
T -= t_i
# This is a min-heap, but we want the longest tasks first
heapq.heappush(heap, -t_i)
# Address a time deficit by dropping tasks
while T < 0:
if not heap:
# Travelled so far we can't do any tasks
return opt
# Subtract because the heap elements are minus the task lengths
T -= heapq.heappop(heap)
# Update the optimal solution so far
opt = max(opt, len(heap))
return opt
Run Code Online (Sandbox Code Playgroud)