문제
내 풀이
풀긴했는데 코드가 너무 더럽다.
from collections import deque
def solution(cap, n, deliveries, pickups):
ans = 0
di = deque()
pi = deque()
for i in range(n):
if deliveries[i] > 0:
di.append(i)
if pickups[i] > 0:
pi.append(i)
while di or pi:
cur_di = None
cur_pi = None
max_i = None
if len(di) > 0:
cur_di = di.pop()
if len(pi) > 0:
cur_pi = pi.pop()
if cur_di is None and cur_pi is not None:
max_i = cur_pi
elif cur_di is not None and cur_pi is None:
max_i = cur_di
else:
max_i = max(cur_di, cur_pi)
ans += (max_i + 1) * 2
for i in range(cap):
if cur_di is not None:
deliveries[cur_di] -= 1
if deliveries[cur_di] == 0 and len(di) > 0:
cur_di = di.pop()
if cur_pi is not None:
pickups[cur_pi] -= 1
if pickups[cur_pi] == 0 and len(pi) > 0:
cur_pi = pi.pop()
if cur_di is not None and deliveries[cur_di] > 0 :
di.append(cur_di)
if cur_pi is not None and pickups[cur_pi] > 0 :
pi.append(cur_pi)
# 여기서 ans에 max(cur_di, cur_pi)를 더해주면 cur_di나 cur_pi가 바뀌어서 오답나옴
return ans
다른사람 풀이
1
https://oh2279.tistory.com/147 (opens in a new tab) 참고
def solution(cap, n, deliveries, pickups):
deliveries = deliveries[::-1]
pickups = pickups[::-1]
answer = 0
have_to_deli = 0
have_to_pick = 0
for i in range(n):
have_to_deli += deliveries[i]
have_to_pick += pickups[i]
# 여기서 만약 have_to_deli가 음수가 된다면
# 다음 i로 갔을 때 이미 전에 들고 갔음을 의미한다.
while have_to_deli > 0 or have_to_pick > 0:
have_to_deli -= cap
have_to_pick -= cap
answer += (n - i) * 2
return answer