신호등마다 빨간불과 초록불 지속시간이 주어진다. 상근이의 트럭이 1초에 1m를 이동한다고 할 때, Lm까지 이동하는데 걸리는 시간을 구해보자.
import sys
input=sys.stdin.readline
def func():
n,l=map(int,input().split())
time=0
place=0
for _ in range(n):
d,r,g=map(int,input().split())
time+=d-place
light=time%(r+g)
if light<=r: # 빨간불인 경우
time+=r-light # 남은 빨간불 시간동안 현재 위치에서 대기
place=d
time+=l-place
return time
print(func())
모듈러 연산을 사용해서 현재 신호등의 불이 빨간불인지 초록불인지 판별하는 것이 핵심이다.
신호등의 개수만큼 for문을 돌리므로 O(n)이다.