统计未覆盖区域大小——基于栈

 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()

 

posted @ 2020-08-05 19:50  玉北  阅读(158)  评论(0编辑  收藏  举报