프로그래머스 - 큐 - 다리를 지나는 트럭
2021. 3. 16. 16:16ㆍAlgorithm
programmers.co.kr/learn/courses/30/lessons/42583
import java.util.LinkedList;
import java.util.Queue;
public class 다리를_지나는_트럭 {
public static void main(String[] args) {
다리를_지나는_트럭 o = new 다리를_지나는_트럭();
System.out.println(o.solution(2, 10, new int[]{7,4,5,6}));
System.out.println(o.solution(100, 100, new int[]{10}));
System.out.println(o.solution(100, 100, new int[]{10,10,10,10,10,10,10,10,10,10}));
}
public int solution(int bridge_length, int weight, int[] truck_weights) {
Bridge bridge = new Bridge(bridge_length, weight);
return bridge.calTime(truck_weights);
}
class Bridge {
private int bridge_length;
private int weight;
private Queue<Integer> bridge = new LinkedList<>();
private int totalWeight;
public Bridge(int bridge_length, int weight) {
this.bridge_length = bridge_length;
this.weight = weight;
totalWeight = 0;
}
public int calTime(int[] truck_weights) {
int time = 0;
int i = 0;
for(int j=0; j<bridge_length; j++) {
bridge.offer(0);
}
while (!bridge.isEmpty()) {
totalWeight -= bridge.poll();
if(i<truck_weights.length && isGoAble(truck_weights[i])) {
bridge.offer(truck_weights[i]);
totalWeight += truck_weights[i];
i++;
} else if(i < truck_weights.length) {
bridge.offer(0);
}
time++;
}
return time;
}
public boolean isGoAble(int newWeight) {
return totalWeight + newWeight <= weight;
}
}
}
알고리즘
- 큐
- 요건에 충족되는 다리 클래스를 구현한다.
- 다리를 큐를 이용하여 구현하였고 다리의 길이만큼 0으로 초기화해준다.
- 마지막 트럭까지 다리의 길이를 유지하고 있다가 마지막 트럭이 지나면 더 이상 offer하지 않는다,
'Algorithm' 카테고리의 다른 글
프로그래머스 - 힙 - 더 맵게 (0) | 2021.03.21 |
---|---|
프로그래머스 - 큐 - 기능개발 (0) | 2021.03.18 |
프로그래머스 - DFS - 단어 변환 (0) | 2021.03.15 |
프로그래머스 - DFS - 네트워크 (0) | 2021.03.15 |
프로그래머스 - DFS - 타겟 넘버 (0) | 2021.03.15 |