|
7 | 7 | public class Solution42583 {
|
8 | 8 |
|
9 | 9 | private static int solution(int bridge_length, int weight, int[] truck_weights){
|
10 |
| - int answer = 1; |
11 |
| - if(truck_weights.length == 1) return bridge_length + 1; |
| 10 | + int answer = 0; |
| 11 | + |
12 | 12 | Deque<Integer> q = new ArrayDeque<>();
|
13 |
| - for(int truck : truck_weights){ |
14 |
| - q.offer( truck ); |
15 |
| - } |
| 13 | + int sum = 0; // 다리를 건너는 트럭들의 무게 합 |
16 | 14 |
|
17 |
| - int bridge = 1; |
18 |
| - int i = 0; |
19 |
| - int max = q.poll(); |
20 |
| - while ( !q.isEmpty() ){ |
21 |
| - if(bridge == bridge_length){ |
22 |
| - max-=truck_weights[i]; |
23 |
| - bridge = 0; |
24 |
| - i++; |
25 |
| - } |
26 |
| - if(max+q.peek()<=weight){ |
27 |
| - max+=q.poll(); |
| 15 | + for(int t : truck_weights) { |
| 16 | + |
| 17 | + while(true) { |
| 18 | + //큐가 비어있다면 다음 트럭 삽입 |
| 19 | + if(q.isEmpty()) { |
| 20 | + q.offer(t); |
| 21 | + sum += t; |
| 22 | + answer++; |
| 23 | + break; |
| 24 | + } |
| 25 | + //큐의 사이즈와 다리의 길이가 같다면 큐에서 큐에서 처음 값을 빼고 최대 무게 - |
| 26 | + else if(q.size() == bridge_length) { |
| 27 | + sum -= q.poll(); |
| 28 | + } |
| 29 | + //큐가 비어있지 않을 때 |
| 30 | + else { |
| 31 | + //다음 트럭이 최대 무게 초과 |
| 32 | + if(sum + t > weight) { |
| 33 | + q.offer(0); |
| 34 | + answer++; |
| 35 | + } |
| 36 | + //다음 트럭이 최대 무게 이내 |
| 37 | + else { |
| 38 | + q.offer(t); |
| 39 | + sum += t; |
| 40 | + answer++; |
| 41 | + break; |
| 42 | + } |
| 43 | + } |
28 | 44 | }
|
29 |
| - bridge++; |
30 |
| - answer++; |
31 | 45 | }
|
32 | 46 |
|
33 |
| - return answer; |
| 47 | + //걸린 시간 + 마지막 트럭의 통과시간(다리의 길이) |
| 48 | + return answer + bridge_length; |
34 | 49 | }
|
35 | 50 |
|
36 |
| - private static int validCompare(int i, int[] truck_weights){ |
37 |
| - if(i<truck_weights.length) return truck_weights[i]; |
38 |
| - return 0; |
39 |
| - } |
40 | 51 |
|
41 | 52 | public static void main ( String[] args ) {
|
42 |
| - int bridge_length = 100; |
43 |
| - int weight = 100; |
44 |
| - int[] truck_weights = {10,10,10,10,10,10,10,10,10,10}; |
| 53 | + int bridge_length = 2; |
| 54 | + int weight = 10; |
| 55 | + int[] truck_weights = {7,4,5,6}; |
45 | 56 | System.out.println(solution(bridge_length,weight,truck_weights));
|
46 | 57 | }
|
47 | 58 | }
|
| 59 | + |
| 60 | +class Truck{ |
| 61 | + int weight; |
| 62 | + int distance; |
| 63 | + |
| 64 | + Truck(int weight, int distance){ |
| 65 | + this.weight = weight; |
| 66 | + this.distance = distance; |
| 67 | + } |
| 68 | +} |
0 commit comments