[JAVA 문제 풀이] 358. 다리를 지나는 트럭

프로그래머스 (42583)
Stupefyee's avatar
Jul 03, 2025
[JAVA 문제 풀이] 358. 다리를 지나는 트럭
notion image
 

내가 작성한 코드

import java.util.*; class Solution { public int solution(int bridge_length, int weight, int[] truck_weights) { Queue<Integer> bridge = new LinkedList<>(); int time = 0; // 경과 시간 int sum = 0; // 현재 다리 위 트럭 무게 합 int idx = 0; // 대기 트럭 인덱스 // 초기: 다리 큐를 bridge_length 만큼 0으로 채움 for (int i = 0; i < bridge_length; i++) { bridge.offer(0); } while (idx < truck_weights.length) { time++; // 매초 증가 sum -= bridge.poll(); // 다리에서 트럭 내리기 (한 칸 앞으로 이동) // 다음 트럭을 다리에 올릴 수 있는지 확인 if (sum + truck_weights[idx] <= weight) { bridge.offer(truck_weights[idx]); // 트럭 올림 sum += truck_weights[idx]; idx++; } else { bridge.offer(0); // 트럭 대신 빈 공간 유지 } } // 마지막 트럭이 다리를 완전히 건너려면 다리 길이만큼 더 기다려야 함 return time + bridge_length; } }
 

다른 사람의 코드

import java.util.*; class Solution { // 트럭 클래스 // 트럭의 무게와 현재 이동 거리를 저장 class Truck { int weight; int move; public Truck(int weight) { this.weight = weight; this.move = 1; } public void moving() { move++; } } public int solution(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; // 시간 초 int 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; } }
 
Share article

stupefyee