쵼쥬 2021. 7. 24. 16:28

문제 설명

트럭 여러 대가 강을 가로지르는 일차선 다리를 정해진 순으로 건너려 합니다. 모든 트럭이 다리를 건너려면 최소 몇 초가 걸리는지 알아내야 합니다. 다리에는 트럭이 최대 bridge_length대 올라갈 수 있으며, 다리는 weight 이하까지의 무게를 견딜 수 있습니다. 단, 다리에 완전히 오르지 않은 트럭의 무게는 무시합니다.

예를 들어, 트럭 2대가 올라갈 수 있고 무게를 10kg까지 견디는 다리가 있습니다. 무게가 [7, 4, 5, 6]kg인 트럭이 순서대로 최단 시간 안에 다리를 건너려면 다음과 같이 건너야 합니다.

 

경과 시간 다리를 지난 트럭 다리를 건너는 트럭 대기 트럭
0 [] [] [7,4,5,6]
1~2 [] [7] [4,5,6]
3 [7] [4] [5,6]
4 [7] [4,5] [6]
5 [7,4] [5] [6]
6~7 [7,4,5] [6] []
8 [7,4,5,6] [] []

따라서, 모든 트럭이 다리를 지나려면 최소 8초가 걸립니다.

solution 함수의 매개변수로 다리에 올라갈 수 있는 트럭 수 bridge_length, 다리가 견딜 수 있는 무게 weight, 트럭 별 무게 truck_weights가 주어집니다. 이때 모든 트럭이 다리를 건너려면 최소 몇 초가 걸리는지 return 하도록 solution 함수를 완성하세요.

 

제한 조건

  • bridge_length는 1 이상 10,000 이하입니다.
  • weight는 1 이상 10,000 이하입니다.
  • truck_weights의 길이는 1 이상 10,000 이하입니다.
  • 모든 트럭의 무게는 1 이상 weight 이하입니다.

 

입출력 예

 

bridge_length weight truck_weights return
2 10 [7,4,5,6] 8
100 100 [10] 101
100 100 [10,10,10,10,10,10,10,10,10,10] 110

출처

※ 공지 - 2020년 4월 06일 테스트케이스가 추가되었습니다.

 


 

풀이 방법 생각

선입선출(FIFO) 문제로 queue를 사용해서 풀 생각을 했다. 각 트럭마다 다리에 올라온 시간을 구하기 위해 Map을 쓸까 생각했는데 queue를 사용한 적이 없어서 queue를 사용해서 풀기로 하고 따로 count를 해주었다. 각 트럭의 count가 다리 길이와 같아지면 queue에서 제거하는 식으로 풀었다.

 

 

내 코드

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

class Solution {
    public int solution(int bridge_length, int weight, int[] truck_weights) {
        int answer = 0;
        Queue<Integer> q = new LinkedList<Integer>();
        ArrayList<Integer> count = new ArrayList<Integer>();

        int index = 0;

        while (true) {
            answer++;
            for (int i = 0; i < count.size(); i++) {
                count.set(i, count.get(i) + 1);
            }

            if(index == truck_weights.length && count.get(count.size() - 1) == bridge_length)
                break;

            if(!count.isEmpty() && count.get(0) == bridge_length){
                count.remove(0);
                q.poll();
            }

            if (index < truck_weights.length && totalQ(q) + truck_weights[index] <= weight && q.size() <= bridge_length) {
                q.offer(truck_weights[index]);
                count.add(0);
                index++;
            }
        }
        return answer;
    }

    int totalQ(Queue<Integer> q) {
        int total = 0;
        for (int i : q) {
            total += i;
        }
        return total;
    }
}

 

다른 사람 풀이

import java.util.*;

class Solution {
    class Truck {
        int weight;
        int move;

        public Truck(int weight) {
            this.weight = weight;
            this.move = 1;
        }

        public void moving() {
            move++;
        }
    }

    public int solution(int bridgeLength, int weight, int[] truckWeights) {
        Queue<Truck> waitQ = new LinkedList<>();
        Queue<Truck> moveQ = new LinkedList<>();

        for (int t : truckWeights) {
            waitQ.offer(new Truck(t));
        }

        int answer = 0;
        int curWeight = 0;

        while (!waitQ.isEmpty() || !moveQ.isEmpty()) {
            answer++;

            if (moveQ.isEmpty()) {
                Truck t = waitQ.poll();
                curWeight += t.weight;
                moveQ.offer(t);
                continue;
            }

            for (Truck t : moveQ) {
                t.moving();
            }

            if (moveQ.peek().move > bridgeLength) {
                Truck t = moveQ.poll();
                curWeight -= t.weight;
            }

            if (!waitQ.isEmpty() && curWeight + waitQ.peek().weight <= weight) {
                Truck t = waitQ.poll();
                curWeight += t.weight;
                moveQ.offer(t);
            }
        }

        return answer;
    }
}

 

문제에서 나온데로 queue를 다리를 지나는 트럭과 대기 트럭 총 두개를 만들어서 푼 코드이다. 모두 빈 queue인지 확인해서 반복문을 돌려준 코드로 문제에서 나온대로 푼 코드로 보인다. 굳이 내가 다르게 생각해서 풀 게 아니라 문제가 주어진대로 풀 방법도 생각해봐야겠다.