알고리즘 풀이/프로그래머스

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

배게 2022. 3. 31. 05:01
728x90
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.util.*;
 
class Solution {
    public int solution(int bridge_length, int max_weight, 
                                        int[] truck_weights){
        
        
        List<Truck> inList = new LinkedList<>();
        Queue<Truck> waitList = new LinkedList<>();
        for(int i=0; i<truck_weights.length; i++){
            waitList.offer(new Truck(truck_weights[i], 0));
        }
        // System.out.println(waitList.size());
        
        int time = 0;
        int curr_weight = 0;
        while(!waitList.isEmpty() || !inList.isEmpty()){
            time++;
            // System.out.println(time);
            
            if(!inList.isEmpty() 
                && inList.get(0).passbyLength == bridge_length){
                curr_weight-=inList.get(0).weight;
                inList.remove(0);
            }
            
            if(!waitList.isEmpty() 
                && curr_weight+waitList.peek().weight<=max_weight){
                curr_weight+=waitList.peek().weight;
                inList.add(waitList.poll());
            }
            
            for(Truck t : inList){
                t.moving();
            }
            
        }
        
        return time;
    }
    
    private class Truck{
        int weight;
        int passbyLength;
        
        public Truck(int weight, int passbyLength){
            this.weight = weight;
            this.passbyLength = passbyLength;
        }
        
        public void moving(){
            passbyLength++;
        }
        
    }
}
cs