프로그래머스/LV2
[프로그래머스 Lv2,python] - 택배 배달과 수거하기
chyam_eun
2025. 5. 26. 17:27
https://school.programmers.co.kr/learn/courses/30/lessons/150369
프로그래머스
SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
def delivery(func, tmp, idx): # tmp는 최대 택배 실을수 있는 갯수
while tmp > 0 and idx >= 0:
if func[idx] > 0:
m = min(tmp, func[idx]) # func[idx]가 tmp를 초과하면 안됨.
tmp -= m
func[idx] -= m
if func[idx] == 0: # 택배를 싣거나 배달 완료했을 때
idx -= 1
return idx # 배달 완료한 곳 이전 idx
def solution(cap, n, deliveries, pickups):
res = 0
d_idx, p_idx = n - 1, n - 1
while d_idx >= 0 or p_idx >= 0:
# 각각의 남은 가장 먼 배달/수거 지점 찾기
while d_idx >= 0 and deliveries[d_idx] == 0:
d_idx -= 1
while p_idx >= 0 and pickups[p_idx] == 0:
p_idx -= 1
if d_idx < 0 and p_idx < 0:
break
# 이번에 가야 할 가장 먼 거리
farthest = max(d_idx, p_idx) + 1
res += farthest * 2 # 왕복 거리
# 각 작업 수행 후 인덱스 갱신
d_idx = delivery(deliveries, cap, d_idx)
p_idx = delivery(pickups, cap, p_idx)
return res
# 시간초과 풀이
def delivery(func,tmp, idx):
while tmp > 0: # 최대한 많이 가도록.
if idx < 0:
break
m = min(tmp,func[idx])
tmp -= m
func[idx] -= m
idx -= 1
return func
def solution(cap, n, deliveries, pickups):
res,idx = 0, n - 1
while idx >= 0 :
tmp = cap
if deliveries[idx] > 0 or pickups[idx] > 0: # 둘중 하나라도 배달하거나 수거할게 있으면
res += idx + 1
deliveries = delivery(deliveries,cap,idx)
pickups = delivery(pickups,cap,idx)
else:
idx -= 1
return res*2 # 왕복