Cute Dog Bopping Head
본문 바로가기
Code IT/Algorithm

[프로그래머스] 다리를 지나는 트럭 - Stack, Queue (Java)

by 찾 2021. 8. 21.
import java.util.LinkedList;
import java.util.Queue;

class Solution {
    public int solution(int bridge_length, int weight, int[] truck_weights) {
        //다리 길이만큼 0을 가지는 큐 생성
        Queue<Integer> acrossQ = new LinkedList<>();
        for(int i=0;i<bridge_length;i++)
            acrossQ.offer(0);
        
        //1) 트럭을 다 올릴 때 까지 weight 고려하며 poll & offer.
        int truckindex=0;
        int second=0;
        int acrossWeight=0;
        while(truckindex<truck_weights.length){
            //다리에 트럭을 올릴 수 없는 경우 가능할 때 까지 poll 진행.
            //다리 위 무게 - 큐의 가장 앞 무게 + 그 다음에 올 트럭 무게가 weight를 넘는다면 poll.
            while(acrossWeight -acrossQ.peek() +truck_weights[truckindex]>weight){
                acrossWeight -= acrossQ.peek();
                acrossQ.poll();
                acrossQ.offer(0);
                second++;
            }
            //다음 트럭을 올릴 수 있는 경우가 되자마자 다음 트럭을 다리큐에 올린다.
            //다리 위 무게 - 큐의 가장 앞 무게 + 그 다음에 올 트럭 무게가 weight를 넘지 않는다면.
            acrossWeight -= acrossQ.peek();
            acrossQ.poll();
            acrossQ.offer(truck_weights[truckindex]);
            acrossWeight += truck_weights[truckindex];
            second++;
            truckindex++;
        }
        
        //2) 마지막 트럭이 건널때까지 poll.
        while(acrossWeight>0){
            acrossWeight -= acrossQ.peek();
            acrossQ.poll();
            second++;
        }
        return second;
    }
}

다리 위 무게 - 큐 가장 앞의 무게 + 그 다음에 올 트럭 무게 !!!!!!!!!!!

계속 다리 위 무게 + 그 다음 트럭 무게 와 weight를 비교했다.

그 과정에서, 큐 가장 앞의 무게가 빠졌을 때 바로 그 다음에 올 트럭을 올릴 수 있음에도 불구하고 1초의 텀을 두고 그 다음 트럭을 올려버려서... 계속 틀렸던 것.

근데 테스트케이스는 다 맞아서, 계속 "틀렸습니다!" 알림을 보며 속상해야 했다.

 

프로그래머스 운영자분들...

테스트케이스 더 주세요 !

댓글