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

2020. 3. 30. 13:18프로그래머스/LEVEL 2

import java.util.*;

class Solution {
    class Truck{
    int weight;
    int enterTime;
    
    Truck(int weight, int enterTime){
        this.weight = weight;
        this.enterTime = enterTime;
    }
}
    
    public int solution(int bridge_length, int weight, int[] truck_weights) {
        int answer = 0;
        int accumulateWeight = 0;
        Queue<Truck> bridge = new LinkedList<>();
        Queue<Truck> waiting = new LinkedList<>();
        
        for(int i=0; i<truck_weights.length; i++){
            waiting.offer(new Truck(truck_weights[i],0)); 
        }
        
        while(!bridge.isEmpty() || !waiting.isEmpty()){
            answer ++;
            if(!bridge.isEmpty()){
                Truck t = bridge.peek();
                if(answer == t.enterTime + bridge_length){
                    accumulateWeight -=t.weight;
                    bridge.poll();
                }
                
            }
            if(!waiting.isEmpty()){
                if(accumulateWeight + waiting.peek().weight <= weight) {
        			Truck t = waiting.poll();
        			accumulateWeight += t.weight;
        			bridge.offer(new Truck(t.weight, answer));
        		}
            }
        }
        return answer;
    }
}