코딩테스트
[프로그래머스] 다리를 지나는 트럭
gajy
2022. 6. 8. 22:07
728x90
https://programmers.co.kr/learn/courses/30/lessons/42583
point 1) 단순하게 Truck 클래스를 생성한다.
point 2) 트럭이 들어오는 부분을 마지막에 실행한다.
point 3) peek를 이용해 확인한다.
import java.util.*;
class Truck {
int weight;
int position;
public Truck(int weight) {
this.weight = weight;
this.position = 1;
}
public void move() {
position++;
}
}
class Solution {
public int solution(int bridge_length, int weight, int[] truck_weights) {
int answer = 0;
int curWeight = 0;
Queue<Truck> waitQ = new LinkedList<>();
Queue<Truck> moveQ = new LinkedList<>();
for(int tw : truck_weights) {
waitQ.offer(new Truck(tw));
}
Truck qItem = null;
while(!waitQ.isEmpty() || !moveQ.isEmpty()) {
answer ++;
if(moveQ.isEmpty()) {
qItem = waitQ.poll();
moveQ.offer(qItem);
curWeight += qItem.weight;
continue;
}
for(Truck t : moveQ) {
t.move();
}
if(moveQ.peek().position > bridge_length) {
curWeight -= moveQ.poll().weight;
}
// 트럭이 들어오는 부분을 마지막에 실행한다.
if(!waitQ.isEmpty() && curWeight + waitQ.peek().weight <= weight) {
Truck t = waitQ.poll();
curWeight += t.weight;
moveQ.offer(t);
}
}
return answer;
}
}
728x90