1. 程式人生 > 實用技巧 >統計未覆蓋區域大小——基於棧

統計未覆蓋區域大小——基於棧

 1 def func():
 2     L, M = map(int, input().strip().split())
 3     left, right = [], {}
 4     for _ in range(M):
 5         temp1, temp2 = map(int, input().strip().split())
 6         left.append(temp1)
 7         right[temp1] = temp2
 8     
 9     left.sort()
10     cur_index = left[0]
11     left_index = 1
12
stack = [right[left[0]]] 13 trees = left[0] 14 while left_index < M: 15 if not stack: 16 trees += left[left_index] - cur_index 17 stack.append(right[left[left_index]]) 18 left_index += 1 19 elif left[left_index] < stack[-1]: 20 stack.append(right[left[left_index]])
21 cur_index = left[left_index] 22 left_index += 1 23 elif left[left_index] >= stack[-1]: 24 trees += left[left_index] - stack[-1] - 1 25 while stack: 26 if left[left_index] > stack[-1]: 27 stack.pop(-1)
28 else: 29 break 30 stack.append(right[left[left_index]]) 31 left_index += 1 32 if stack: 33 trees += L - stack[-1] 34 35 print(trees) 36 37 38 if __name__ == "__main__": 39 func()