개발 공부

(프로그래머스)(자바) 다리를 지나는 트럭 본문

알고리즘

(프로그래머스)(자바) 다리를 지나는 트럭

아이셩짱셩 2021. 7. 7. 16:32

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

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

import java.util.*;

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