📚 Data Architect/Programmers
고득점 Kit - Stack & Queue (다리를 지나는 트럭)
신건우
2023. 4. 12. 12:46
💡 문제 파악
트럭 여러 대가 강을 가로지르는 일차선 다리를 정해진 순으로 건너려 합니다.
모든 트럭이 다리를 건너려면 최소 몇 초가 걸리는지 알아내야 합니다.
다리에는 트럭이 최대 bridge_length대 올라갈 수 있으며,
다리는 weight 이하까지의 무게를 견딜 수 있습니다.
단, 다리에 완전히 오르지 않은 트럭의 무게는 무시합니다.
예를 들어, 트럭 2대가 올라갈 수 있고 무게를 10kg까지 견디는 다리가 있습니다. 무게가 [7, 4, 5, 6]kg인 트럭이 순서대로 최단 시간 안에 다리를 건너려면 다음과 같이 건너야 합니다.
경과 시간 | 다리를 지난 트럭 | 다리를 건너는 트럭 | 대기 트럭 |
---|---|---|---|
0 | [] | [] | [7,4,5,6] |
1~2 | [] | [7] | [4,5,6] |
3 | [7] | [4] | [5,6] |
4 | [7] | [4,5] | [6] |
5 | [7,4] | [5] | [6] |
6~7 | [7,4,5] | [6] | [] |
8 | [7,4,5,6] | [] | [] |
따라서, 모든 트럭이 다리를 지나려면 최소 8초가 걸립니다.
solution 함수의 매개변수로 다리에 올라갈 수 있는 트럭 수 bridge_length, 다리가 견딜 수 있는 무게 weight, 트럭 별 무게 truck_weights가 주어집니다.
이때 모든 트럭이 다리를 건너려면 최소 몇 초가 걸리는지 return 하도록 solution 함수를 완성하세요.
제한 조건
- bridge_length는 1 이상 10,000 이하입니다.
- weight는 1 이상 10,000 이하입니다.
- truck_weights의 길이는 1 이상 10,000 이하입니다.
- 모든 트럭의 무게는 1 이상 weight 이하입니다.
입출력 예
bridge_length | weight | truck_weights | return |
---|---|---|---|
2 | 10 | [7,4,5,6] | 8 |
100 | 100 | [10] | 101 |
100 | 100 | [10,10,10,10,10 |
풀이
설명은 주석으로 대신함.
public class 다리를지나는트럭 {
public static void main(String[] args) {
int[] n = {7, 4, 5, 6};
System.out.println(solution(2, 10, n));
}
public static int solution(int bridge_length, int weight, int[] truck_weights) {
Queue<Integer> queue = new LinkedList<Integer>();
int time=0, sum=0;
for (int i = 0; i < truck_weights.length; i++) {
int truck = truck_weights[i];
while (true) {
// 큐가 비어있을 경우 다리를 건너게 한다
if (queue.isEmpty()) {
queue.add(truck_weights[i]);
sum += truck; // 트럭 무게의 합을 구한다.
time++; // 다리에 건너는 행동을 했으므로 시간 +1
break;
// 트럭의 수가 length와 같기 떄문에 트럭이 다리를 다 지나서 다리에서 빠져나와야 한다.
} else if (queue.size() == bridge_length) {
sum -= queue.poll();
} else {
// 다리 무게에 여유가 있을 때 큐에 다음 트럭을 넣는다.
if (sum + truck <= weight) {
queue.add(truck);
sum += truck;
time++;
break;
// 무게가 초과하면 앞의 트럭을 전진시키기 위해 0을 넣는다 (큐의 size를 늘리기 위해)
} else {
queue.add(0);
time++;
}
}
}
}
return time + bridge_length;
}
}
다른 사람의 풀이
static class Truck {
int weight;
int move;
public Truck(int weight) {
this.weight = weight;
this.move = 1;
}
public void moving() {
move++;
}
}
public static int solution2(int bridgeLength, int weight, int[] truckWeights) {
Queue<Truck> waitQ = new LinkedList<>();
Queue<Truck> moveQ = new LinkedList<>();
for (int t : truckWeights) {
waitQ.offer(new Truck(t));
}
int answer = 0, 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();
}
if (moveQ.peek().move > bridgeLength) {
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;
}
}