PROGRAMMERS 스택/큐 다리를 지나는 트럭

less than 1 minute read

  1. 변수

    class Truck {
        int weight, time; 
    }
    int totalTime  // 총 걸린 시간
    int curBWeight // 현재 다리의 무게 (주어지는 무게 넘지않아야 해)
    int truckIdx   // 대기 트럭배열의 index 값
    Queue<Integer> bridge = new LinkedList<Integer>();
    
  2. 구현로직

    1. 다리의 무게가 가능하면 트럭을 다리에 넣어줌

    2. 다리의 길이만큼 시간이 지난 트럭이 있는지 check

      • 있다면 poll 해준다
    3. 시간(totalTime) 증가

  3. 코드

    import java.util.*;
       
    class Solution {
        static class Truck{
            int w, time;
               
            public Truck(int w, int time){
                this.w = w;
                this.time = time;
            }
        }
           
        public int solution(int bridge_length, int weight, int[] truck_weights) {
            int totalTime = 1; // 경과 시간
            int curBWeight = 0; // 현재 다리의 무게
            int truckIdx = 0; 
            Queue<Truck> q = new LinkedList<Truck>();
               
            while(true){
                if(truckIdx>=1 && (totalTime-bridge_length)==q.peek().time){
                        curBWeight -=q.peek().w;
                        q.poll();
                       
                        // 기저조건
                        if(truckIdx == truck_weights.length && q.isEmpty()) break;
                    }
                   
                if(truckIdx < truck_weights.length && curBWeight+truck_weights[truckIdx] <= weight) {
                    q.add(new Truck(truck_weights[truckIdx], totalTime));
                    curBWeight +=truck_weights[truckIdx];
                    truckIdx++;
                }
                   
                totalTime++;
            }
                      
            return totalTime;
        }
    }
    
  4. 느낀점

    • 완전 탐색같이 정해진 경우 for문
    • 시뮬레이션은 while문 (몇 번을 돌지 모르기때문에)

문제 링크 : 프로그래머스 스택/큐 다리를 지나는 트럭

Leave a comment