java 프로그래머스 [스택/큐] _다리를 지나는 트럭
2021. 4. 29. 22:19ㆍ프로그래머스 알고리즘/코딩 테스트 고득점 Kit
반응형
출제 링크 : programmers.co.kr/learn/courses/30/lessons/42583
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;
}
}
반응형