티스토리 뷰

Link

Code

import java.util.*;
class Solution {
    public int solution(int bridge_length, int weight, int[] truck_weights) {
        int answer = 0;
        HashMap<Integer, Integer> map = new HashMap<>();
        Queue<Integer> queue = new LinkedList<>();
        Queue<Integer> queue2 = new LinkedList<>();
        for (int i = 0; i < truck_weights.length; i++) {
            map.put(i,0);
            queue.add(truck_weights[i]);
            queue2.add(truck_weights[i]);
        }
        int current = 0 ;
        int prev = 0 ;

        while(!queue2.isEmpty()){
            answer ++ ;
            int Q = 0 ;
            int W = 0 ;
            if(queue.isEmpty()){

            }

            else if(weight- queue.peek() >= 0 ){
                if(W!=1) {
                    current++;
                    weight = weight - queue.poll();
                    Q++;
                }else{
                    W=0;
                }
            }
            for(int i =prev ; i <current; i++){
                if(map.get(i) < bridge_length){
                    map.put(i, map.get(i)+1);
                }
                else if(map.get(i) == bridge_length){
                    map.put(i, map.get(i)+1);
                    weight = weight + queue2.poll();
                    prev ++;
                    if(queue.isEmpty()){

                    }
                    else if(weight- queue.peek() >= 0 ){
                        if(Q!=1) {
                            current++;
                            weight = weight - queue.poll();
                            W++;
                        }{
                            Q=0;
                        }
                    }
                }
            }
        }
        return answer;
    }
}

 

Explain

1. 트럭이 지났는지 안지났는지 확인하기위해 안지나간 트럭 Queue, 지나간 트럭 Queue 생성하고 다리에 있을때는 map에 넣는다.

2. map에 들어왔을 때는 안지나간 트럭에서 무게만큼 더함

3. map에서는 다리에서 1씩 증가하고 길이가 되었을 시 map에 나갈때는 무게만큼 뺌

4. answer은 행동이 시작할 때 부터 1씩 증가