[알고리즘] 프로그래머스 - 다리를 지나는 트럭

June·2021년 6월 26일
0

알고리즘

목록 보기
224/260

프로그래머스 - 다리를 지나는 트럭

내 풀이

public class programmers_42583 {

    public static void main(String[] args) throws IOException {
        System.out.println(solution(2, 10, new int[]{7, 4, 5, 6}));
        System.out.println(solution(100, 100, new int[]{10}));
        System.out.println(solution(100, 100, new int[]{10,10,10,10,10,10,10,10,10,10}));

    }

    public static int solution(int bridge_length, int weight, int[] truck_weights) {
        int answer = 0;
        Queue<Integer> q = new LinkedList<>();
        for (int truck : truck_weights) {
            q.add(truck);
        }
        Queue<Integer> bridge = new LinkedList<>();
        for (int i = 0; i < bridge_length; i++) {
            bridge.add(0);
        }

        int curBridgeSum = 0;
        while (!q.isEmpty() || curBridgeSum != 0) {
            answer++;
            int poll = bridge.poll();
            if (poll != 0) { //차가 나온다면
                curBridgeSum -= poll;
            }
            int newTruck = 0;
            if (!q.isEmpty() && (curBridgeSum + q.peek() <= weight)) {
                newTruck = q.poll();
                curBridgeSum += newTruck;
            }
            bridge.add(newTruck);
        }
        return answer;
    }
}

차가 다리에서 나오는 것과 들어오는 것이 현실에서는 동시에 일어나지만 프로그래밍에서는 순차를 두고 발생하기 때문에 뭐가 먼저 일어나야하는지 잘 고려해야한다.

처음에는 다리에 진입하는 것을 먼저 고려했는데, 차가 나가는 순간 무게 기준을 넘지 않는다면 차가 들어올 수 있기 때문에 먼저 나가고 들어오는 것으로 구현하는 것이 이해하는데 더 편하다.

또한 다리의 길이를 고려해야하는데 처음에는 어떻게 구현할지 고민하다가 실제로 다리를 0으로 채워서 길이를 만들어주면 보다 편하게 문제를 풀 수 있다.

0개의 댓글