1 回答

TA貢獻1719條經驗 獲得超6個贊
您實施了一種蠻力方法來解決它。您的代碼運行緩慢,時間復雜度 O(N^2),但您可以在 O(N*log(N)) 中執行此操作
而不是檢查 ,對數組進行排序并使用 C 或 J 的最后一個結束時間活動進行檢查。( 貪婪的方式解決它 )notOverlap(activity, arr)
在對數組進行排序之前,必須存儲活動的索引。
這是我的解決方案,但在閱讀解決方案之前,請嘗試自己實現它
for testcasei in range(1, 1 + int(input())):
n = int(input())
acts = []
for index in range(n):
start, end = map(int, input().split())
acts.append((start, end, index)) # store also the index
acts.sort(reverse=True) # sort by starting time reversed
# so the first activity go to the last
d = ['']*n # construct the array for the answer
cnow = jnow = 0 # next time C or J are available
impossible = False # not impossible for now
while acts: # while there is an activity
start_time, end_time, index = acts.pop()
if cnow <= start_time: # C is available to do the activity
cnow = end_time
d[index] = 'C'
elif jnow <= start_time:
jnow = end_time
d[index] = 'J'
else: # both are'nt available
impossible = True
break
if impossible:
d = 'IMPOSSIBLE'
else:
d = ''.join(d) # convert the array to string
print("Case #%d: %s" % (testcasei, d))
我希望您找到這些信息,并幫助您理解并保持努力工作。
添加回答
舉報