1일 1PS 28일차!

📚 문제


Lv 2

  • 사실상 택배 배달 문제 두 개를 동시에 진행시키면 된다.
  • 택배가 배달갈 때와 돌아올 때 모두 가능한 용량을 가장 먼 곳에서부터 사용하면 된다.
  • 이때 배달과 수거 모두에서 가장 마지막 index 번호의 배달이나 수거 양이 0일 경우를 주의하면 된다.
    • 즉, 가장 먼 곳에서 cap 개수만큼 배달했으면 배달할 것이 없는 곳들을 모두 제외하고 다음으로 가장 먼 곳에 배달할 것이 있는 index 를 찾아 저장해야한다.

💡 포인트


  1. 처음 시작에 가장 멀리 배달 혹은 수거해야하는 index 를 저장한다.
  2. cap 개수만큼에서 가장 먼 배달, 수거부터 진행시키고 다음 멀리 있는 배달, 수거의 index 를 저장한다.
  3. 이때 가장 멀었던 길이를 answer 에 합한다.
  4. 배달, 수거하는 index 가 -1 이 될 때까지 반복한다.
  5. 이때 answer 는 왕복이므로 * 2 를 출력한다.

💻 코드



def solution(cap, n, deliveries, pickups):
    answer = 0
    last_delivery = last_pickups = n - 1
    for i in range(n-1, -1, -1):
        if deliveries[i] != 0:
            last_delivery = i
            break
        if i == 0 and deliveries[i] == 0:
            last_delivery = -1
    for i in range(n-1, -1, -1):
        if pickups[i] != 0:
            last_pickups = i
            break
        if i == 0 and pickups[i] == 0:
            last_pickups = -1


    while last_delivery != -1 or last_pickups != -1:
        answer += max(last_delivery, last_pickups) + 1
        current_cap = cap
        for i in range(last_delivery, -1, -1):
            if deliveries[i] <= current_cap:
                current_cap -= deliveries[i]
                deliveries[i] = 0
            else:
                deliveries[i] -= current_cap
                current_cap = 0

            if i == 0 and deliveries[i] == 0:
                last_delivery = -1
                break

            if current_cap == 0 and deliveries[i] != 0:
                last_delivery = i
                break

        current_cap = cap
        for i in range(last_pickups, -1, -1):
            if pickups[i] <= current_cap:
                current_cap -= pickups[i]
                pickups[i] = 0
            else:
                pickups[i] -= current_cap
                current_cap = 0

            if i == 0 and pickups[i] == 0:
                last_pickups = -1
                break

            if current_cap == 0 and pickups[i] != 0:
                last_pickups = i
                break

    return answer * 2


업데이트:

댓글남기기