본문 바로가기
알고리즘/프로그래머스

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

by justkeepgoing 2021. 1. 6.
728x90
반응형

1. 문제

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

 

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

트럭 여러 대가 강을 가로지르는 일 차선 다리를 정해진 순으로 건너려 합니다. 모든 트럭이 다리를 건너려면 최소 몇 초가 걸리는지 알아내야 합니다. 트럭은 1초에 1만큼 움직이며, 다리 길이

programmers.co.kr

2. 풀이

  • Queue를 활용하여 구현

3. 코드

import java.util.*;
class Solution {
     static class Truck{
        int num, time;

        public Truck(int num, int time) {
            this.num = num;
            this.time = time;
        }
    }
    public int solution(int bridge_length, int weight, int[] truck_weights) {
           int answer = 0;
        Queue<Truck>que = new LinkedList<>();
        int len = truck_weights.length;
        int idx=0, totalWeight=0;
        while(!que.isEmpty() || idx != len){
            if(!que.isEmpty() && answer-que.peek().time==bridge_length){
                totalWeight-=truck_weights[que.poll().num];
            }
            if(idx != len && totalWeight + truck_weights[idx]<=weight){
                que.offer(new Truck(idx,answer));
                totalWeight += truck_weights[idx++];
            }
            answer++;
        }
        return answer;
    }
}
반응형

 

반응형