给定间隔列表interval [] ,其中每个间隔包含两个整数L和R ,任务是将间隔分配给两个不同的处理器,以使它们对于每个处理器而言都不是重叠的间隔。要将间隔[i]分配给第一个处理器,请打印“ F”,然后将其分配给第二个处理器,请打印“ S”。
注意:如果没有可能的解决方法,请打印-1。
例子:
Input: interval[] = {{360, 480}, {420, 540}, {600, 660}}
Output: S, F, S
Explanation:
The intervals assigned to processors are –
Intervals of First Processor {{420, 540}}
Intervals of Second Processor {{360, 480}, {600, 660}}
As there are no overlapping intervals for each processor, it will be a valid solution.
Input: interval[] = {{99, 150}, {1, 100}, {100, 301}, {2, 5}, {150, 250}}
Output: S, F, F, S, S
Explanation:
The intervals assigned to processors are –
Intervals of First Processor {{1, 100}, {100, 301}}
Intervals of Second Processor {{99, 150}, {2, 5}, {150, 250}}
As there are no overlapping intervals for each processor, it will be a valid solution.
方法:想法是使用贪婪算法将间隔分配给处理器。
如果处理器的最高结束时间小于或等于某个间隔的开始时间,则可以将此间隔分配给处理器。否则,请检查其他处理器。如果无法将任何时间间隔分配给任何处理器,则没有可能的解决方案。
下面是该方法步骤的说明:
- 与当前问题一样,我们必须根据间隔的顺序进行打印。因此,要保存间隔的顺序,请将间隔与其索引配对。
- 按时间间隔对时间间隔进行排序。即L。
- 遍历时间间隔,并将时间间隔分配给处理器,如下所示:
if (interval[i][0] >= firstProcessorEndTime) answer[interval[i]] = "F" firstProcessorEndTime = max(firstProcessorEndTime, interval[i][0]) else if (interval[i][0] >= secondProcessorEndTime) answer[interval[i]] = "S" secondProcessorEndTime = max(secondProcessorEndTime, interval[i][0]) else print(-1)
下面是上述方法的实现:
Python3
# Python implementation for intervals
# scheduling to two processors such
# that there are no overlapping intervals
# Function to assign the intervals
# to two different processors
def assignIntervals(interval, n):
# Loop to pair the interval
# with their indices
for i in range(n):
interval[i].append(i)
# sorting the interval by
# their startb times
interval.sort(key = lambda x: x[0])
firstEndTime = -1
secondEndTime = -1
fin = ''
flag = False
# Loop to iterate over the
# intervals with their start time
for i in range(n):
if interval[i][0] >= firstEndTime:
firstEndTime = interval[i][1]
interval[i].append('S')
elif interval[i][0] >= secondEndTime:
secondEndTime = interval[i][1]
interval[i].append('F')
else:
flag = True
break
# Condition to check if there
# is a possible solution
if flag:
print(-1)
else:
form = ['']*n
for i in range(n):
indi = interval[i][2]
form[indi] = interval[i][3]
# form = ''.join(form)
print(form, ", ")
# Driver Code
if __name__ == "__main__":
intervals = [[360, 480], [420, 540], [600, 660]]
# Function Call
assignIntervals(intervals, len(intervals))
['S', 'F', 'S'] ,