https://school.programmers.co.kr/learn/courses/30/lessons/42583
그대로 Queue 이용해서 구현하면 되는데
항상 시간과 연관된 문제에서 시간을 어떻게 처리해야 할지 어렵다
다리에서 트럭이 나가는 시각 = 트럭이 다리에 진입한 시각 + 다리의 길이
import java.util.*;
class Solution {
static int MAX_ENDURE_WEIGHT;
static int BRIDGE_LENGTH;
// bridge_length : 다리에 올라갈 수 있는 트럭의 수
// weight : 다리가 견딜 수 있는 무게
// truck_weights : 트럭별 무게
static int onBridgeWeight = 0;
public int solution(int bridge_length, int weight, int[] truck_weights) {
MAX_ENDURE_WEIGHT = weight;
BRIDGE_LENGTH = bridge_length;
Deque<Car> bridge = new ArrayDeque<>();
int time = 0;
int inIdx = 0;
while(!(bridge.isEmpty() && inIdx >= truck_weights.length)) {
time += 1;
outBridge(bridge, time); // 일단 내보낸다
if(inIdx < truck_weights.length) { // 새로 다리에 진입할 트럭이 있는가
boolean inSuccess = inBridge(bridge, time, truck_weights[inIdx]);
if(inSuccess){ // 진입에 성공하면
inIdx += 1; // 다음 진입할 트럭을 선정한다
}
}
//System.out.println(time + " : " + bridge + onBridgeWeight);
}
return time;
}
// 1. 내보내기
static void outBridge(Deque<Car> bridge, int curTime) {
if(!bridge.isEmpty() && bridge.peek().outTime == curTime) {
onBridgeWeight -= bridge.pollFirst().weight;
}
}
// 2. 다리에 올라갈 수 있는지 판단
static boolean inBridge(Deque<Car> bridge, int curTime, int newTruckWeight) {
if(onBridgeWeight + newTruckWeight <= MAX_ENDURE_WEIGHT) {
bridge.addLast(new Car(curTime + BRIDGE_LENGTH, newTruckWeight));
onBridgeWeight += newTruckWeight;
return true;
}
return false;
}
static class Car {
int outTime, weight;
Car(int outTime, int weight) {
this.outTime = outTime;
this.weight = weight;
}
@Override
public String toString(){
return ""+weight;
}
}
}
[BJ] 1976 : 여행가자 - unsolved (0) | 2025.01.19 |
---|---|
[프로그래머스] 기지국 설치 - unsolved (0) | 2025.01.16 |
[프로그래머스] 석유시추 (0) | 2025.01.15 |
[프로그래머스] 등굣길 : unsolved (0) | 2025.01.15 |
[BJ] 1107 : 리모컨 : unsolved (0) | 2025.01.15 |