APCS Mar 2016 - b966 Q3 [Python]
Problem statement:
Given several segments on a one-dimensional coordinate axis, find their total covered length. Count overlapping portions only once. For example, the four segments (5, 6), (1, 2), (4, 8), and (7, 9) cover a total length of 6, as shown below.

def main():
# 讀取線段數量
n = int(input())
segments = []
# 讀取每個線段的起點和終點
for _ in range(n):
L, R = map(int, input().split())
segments.append((L, R))
# 將線段按照起點進行排序
segments.sort(key=lambda x: x[0])
# 合併線段
covered_length = 0
current_start, current_end = -1, -1
for start, end in segments:
if start > current_end:
# 如果當前線段與前一線段不重疊,加上前一線段的長度(因為上一步不知道下一個是否比自己大)
covered_length += current_end - current_start
current_start, current_end = start, end
else:
# 如果重疊,延伸線段的結束點
current_end = max(current_end, end)
# 加上最後一個線段的長度
covered_length += current_end - current_start
# 輸出結果
print(covered_length)
if __name__ == "__main__":
main()
Key concepts
-
map syntax:
map(func, obj)Example:
map(int,input(),split()) -
sort syntax:
[(array)].sort(key=func)Example:
the_list = [(0,6),(3,8),(5,7),(2,5),(1,10),(8,12),(7,10)] the_list.sort(key= lamba x:x[0])
This article was translated from Traditional Chinese by AI. Meaning or wording may differ; please refer to the Traditional Chinese original as the authoritative version.