백준 2170 - 선 긋기 (Python)
Updated:
라인 스위핑을 이용해서 풀었습니다.
먼저 시작점을 기준으로 오름차순 정렬해서 조건에 맞게 처리했습니다.
전체코드
import sys
input = sys.stdin.readline
N = int(input())
lines = [tuple(map(int, input().split())) for _ in range(N)]
lines.sort()
ans = 0
bS = bE = 0
for s, e in lines:
if not ans:
ans = abs(e - s)
bS = s
bE = e
continue
if bS <= s and bE >= e:
continue
ans += abs(e - s)
if bE > s:
ans -= abs(bE - s)
bS = s
bE = e
print(ans)