java 프로그래머스 [스택/큐] _다리를 지나는 트럭

2021. 4. 29. 22:19프로그래머스 알고리즘/코딩 테스트 고득점 Kit

반응형

 

출제 링크 : programmers.co.kr/learn/courses/30/lessons/42583

 

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

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

programmers.co.kr

 


 

import java.util.LinkedList;
import java.util.Queue;
class Solution {

	class Truck {
		int weight;
		int move;

		public Truck(int weight) {
			this.weight = weight;
			this.move = 1;
		}

		public void moving() {
			move++;
		}
	}

	public int solution(int bridge_length, int weight, int[] truck_weights) {

		Queue<Truck> waitQ = new LinkedList<Truck>();
		Queue<Truck> moveQ = new LinkedList<Truck>();

		for (int t : truck_weights) {
			waitQ.offer(new Truck(t));
		}

		int answer = 0;
		int curWeight = 0;

		while (!waitQ.isEmpty() || !moveQ.isEmpty()) {
			answer++;

			// 움직이는 트럭이 없을 경우
			if (moveQ.isEmpty()) {
				Truck t = waitQ.poll();
				curWeight += t.weight;
				moveQ.offer(t);
				continue;
			}

			// 트럭을 움직임
			for (Truck t : moveQ) {
				t.moving();
			}

			// 움직이는 트럭 맨위를 꺼내서 다리 길이와 비교함 (peek은 실제로 꺼내지 않음)
			if (moveQ.peek().move > bridge_length) {
				Truck t = moveQ.poll();
				curWeight -= t.weight;
			}

			// 현재 기다리는 트럭이 있고 (현재 다리의 무게 + 다음 트럭의 무게) <= 다리의 하중 보다 작다면 트럭 추가
			if (!waitQ.isEmpty() && curWeight + waitQ.peek().weight <= weight) {
				Truck t = waitQ.poll();
				curWeight += t.weight;
				moveQ.offer(t);
			}
		}

		return answer;
	}
}

 

반응형