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

2021. 3. 16. 16:16Algorithm

programmers.co.kr/learn/courses/30/lessons/42583

 

코딩테스트 연습 - 다리를 지나는 트럭

트럭 여러 대가 강을 가로지르는 일 차선 다리를 정해진 순으로 건너려 합니다. 모든 트럭이 다리를 건너려면 최소 몇 초가 걸리는지 알아내야 합니다. 트럭은 1초에 1만큼 움직이며, 다리 길이

programmers.co.kr

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

public class 다리를_지나는_트럭 {
    public static void main(String[] args) {
        다리를_지나는_트럭 o = new 다리를_지나는_트럭();
        System.out.println(o.solution(2, 10, new int[]{7,4,5,6}));
        System.out.println(o.solution(100, 100, new int[]{10}));
        System.out.println(o.solution(100, 100, new int[]{10,10,10,10,10,10,10,10,10,10}));
    }

    public int solution(int bridge_length, int weight, int[] truck_weights) {
        Bridge bridge = new Bridge(bridge_length, weight);
        return bridge.calTime(truck_weights);
    }

    class Bridge {
        private int bridge_length;
        private int weight;
        private Queue<Integer> bridge = new LinkedList<>();
        private int totalWeight;

        public Bridge(int bridge_length, int weight) {
            this.bridge_length = bridge_length;
            this.weight = weight;
            totalWeight = 0;
        }

        public int calTime(int[] truck_weights) {
            int time = 0;
            int i = 0;

            for(int j=0; j<bridge_length; j++) {
                bridge.offer(0);
            }

            while (!bridge.isEmpty()) {
                totalWeight -= bridge.poll();

                if(i<truck_weights.length && isGoAble(truck_weights[i])) {
                    bridge.offer(truck_weights[i]);
                    totalWeight += truck_weights[i];
                    i++;
                } else if(i < truck_weights.length) {
                    bridge.offer(0);
                }

                time++;
            }

            return time;
        }

        public boolean isGoAble(int newWeight) {
            return totalWeight + newWeight <= weight;
        }
    }
}

 

알고리즘

  • 요건에 충족되는 다리 클래스를 구현한다.
  • 다리를 큐를 이용하여 구현하였고 다리의 길이만큼 0으로 초기화해준다.
  • 마지막 트럭까지 다리의 길이를 유지하고 있다가 마지막 트럭이 지나면 더 이상 offer하지 않는다,