[Programmers] 다리를 지나는 트럭 - 스택/큐

동민·2021년 3월 11일
0
import java.util.LinkedList;
import java.util.Queue;

// 다리를 지나는 트럭 - 스택/큐
public class Truck {

	public int solution(int bridge_length, int weight, int[] truck_weights) {
		int answer = 1;

		Queue<Integer> bridgeQ = new LinkedList<>(); // 다리를 건너고 있는 트럭을 저장할 큐
		Queue<Integer> truckQ = new LinkedList<>(); // 대기하고 있는 트럭을 저장할 큐

		for (int ele : truck_weights) {
			truckQ.offer(ele);
		}
		for (int i = 0; i < bridge_length - 1; i++) { // 다리 큐에 다리의 길이(bridge_length)-1 만큼 0으로 채움
			bridgeQ.offer(0); 
		}

		int current_weight = 0; // 현제 다리에 올라가있는 모든 트럭의 무게의 합
		while (!bridgeQ.isEmpty()) {
			if (!truckQ.isEmpty()) { // 트럭큐가 비어있을 때 qeek() 하는 예외(NullPointException)을 처리
				if (current_weight + truckQ.peek() <= weight) { // 다리의 최대 중량을 초과하지 않을 때
					current_weight += truckQ.peek(); 
					bridgeQ.offer(truckQ.poll()); // 맨 앞에 대기하고 있는 트럭 한대를 다리에 올림
				} else {
					bridgeQ.offer(0); // 중량을 초과하는 경우 0으로 채움
				}
			}
			current_weight -= bridgeQ.poll(); // bridge_length 만큼 움직인 트럭을 다리큐에서 제거
			answer++; // 1초씩 증가 
		}
		return answer;
	}

	public static void main(String[] args) {

		Truck s = new Truck();

		int[] truck_weights1 = { 7, 4, 5, 6 };
		int[] truck_weights2 = { 10 };
		int[] truck_weights3 = { 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 };

		System.out.println(s.solution(2, 10, truck_weights1)); // 8
		System.out.println(s.solution(100, 100, truck_weights2)); // 101
		System.out.println(s.solution(100, 100, truck_weights3)); // 110

	}
}
profile
BE Developer

0개의 댓글