트럭 여러 대가 강을 가로지르는 일 차선 다리를 정해진 순으로 건너려 합니다. 모든 트럭이 다리를 건너려면 최소 몇 초가 걸리는지 알아내야 합니다. 트럭은 1초에 1만큼 움직이며, 다리 길이는 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 | weight | truck_weights | return |
2 | 10 | [7,4,5,6] | 8 |
100 | 100 | [10] | 101 |
100 | 100 | [10,10,10,10,10,10,10,10,10,10] | 110 |
import java.util.LinkedList;
import java.util.Queue;
class Main {
public static void main(String[] args) {
int[] weights = {7, 4, 5, 6};
int[] weights1 = {10};
int[] weights2 = {10,10,10,10,10,10,10,10,10,10};
System.out.println(solution(2, 10, weights));
System.out.println(solution(100, 100, weights1));
System.out.println(solution(100, 100, weights2));
}
static int solution(int bridge_length, int weight, int[] truck_weights) {
int answer = 0;
Queue<Truck> line = new LinkedList<>();
Queue<Truck> trucks = new LinkedList<>();
for (int t : truck_weights) { //트럭을 queue으로 변경
trucks.offer(new Truck(t));
}
Truck ft = trucks.poll().goTruck(); //트럭 무게
line.offer(ft); //첫번째 트럭은 미리 대입
answer++; //첫번째 트럭이 출발해 1초 증가
int currentWeight = ft.weight; //현재 다리 위 무게
do {
Truck nextT = trucks.peek();
int lSize = line.size();
for (int i = 0; i < lSize; i++) { //라인 위에 트럭들 거리를 증가 > 거리가 bridge 길이 끝에 도달하면 바로 버립니다.
Truck lt = line.poll().goTruck();
if (lt.distance > bridge_length) {
currentWeight -= lt.weight;
} else {
line.offer(lt);
}
}
if (nextT != null) {
if ((currentWeight + nextT.weight) <= weight) { //트럭을 더 올릴 수 있다면
currentWeight += nextT.weight; //가중된 트럭 무게 증가
line.offer(trucks.poll().goTruck());
}
}
answer++;
} while (!line.isEmpty() || !trucks.isEmpty());
return answer;
}
static class Truck {
int weight;
int distance;
public Truck(int weight) {
this.weight = weight;
this.distance = 0;
}
public Truck goTruck() {
distance++;
return this;
}
}
}
[백준 No.10825] 국영수 (정렬) (0) | 2020.10.28 |
---|---|
[백준 No.18310] 안테나 (정렬, 수학) (0) | 2020.10.28 |
[프로그래머스 Lv2] 프린터 (큐) (0) | 2020.10.27 |
[백준 No.10816] 숫자카드2 (이진 탐색) (0) | 2020.10.27 |
숫자카드 2 Tip (0) | 2020.10.27 |