11import java .util .*;
22class Solution {
33 public int solution (int bridge_length , int weight , int [] truck_weights ) {
4- Queue <Integer > queue = new LinkedList <>();
5- int time = 0 ;
6- int idx = 0 ;
7- while (idx < truck_weights .length ){
8- if (queue .isEmpty ()){
9- queue .add (truck_weights [idx ++]);
10- time ++;
11- continue ;
12- }
13-
14- // 다리 길이보다 짧을 경우
15- if (queue .size () < bridge_length ){
16- // 큐의 합
17- long current = queue .stream ()
18- .mapToLong (Integer ::longValue )
19- .sum ();
20-
21- // 하중 초과
22- if (current + truck_weights [idx ] > weight ){
23- queue .offer (0 ); // 다리의 시간 흐름 체크를 위해 빈 공간 추가
24- time ++;
25- }else {
26- queue .add (truck_weights [idx ++]);
27- time ++;
28- }
29- } else if (queue .size () == bridge_length ) {
30- queue .poll (); // 내림
31-
32- long current = queue .stream ()
33- .mapToLong (Integer ::longValue )
34- .sum ();
35- if (current + truck_weights [idx ] > weight ){
36- queue .offer (0 );
37- time ++;
38- }else {
39- queue .add (truck_weights [idx ++]);
40- time ++;
4+ Queue <Integer > readyQueue = new LinkedList <>();
5+ // [무게,경과시간]
6+ Queue <int []> bridgeQueue = new LinkedList <>();
7+ for (int truck :truck_weights ){
8+ readyQueue .offer (truck );
9+ }
10+
11+ int weightSum = 0 ;
12+ int currentTime = 0 ;
13+ int startTime ;
14+ while (!readyQueue .isEmpty ()){
15+ currentTime ++;
16+ int truck = readyQueue .peek ();
17+ if (!bridgeQueue .isEmpty ()){
18+ startTime = bridgeQueue .peek ()[1 ]; // 다리에 올라간 시간
19+ if (currentTime - startTime == bridge_length ){
20+ // 완전히 다리에서 내려감
21+ weightSum -= bridgeQueue .poll ()[0 ];
4122 }
4223 }
24+
25+ if (truck + weightSum <= weight ){
26+ bridgeQueue .offer (new int []{truck ,currentTime }); // 다리에 올림
27+ weightSum +=truck ; // 무게 추가
28+ readyQueue .poll ();
29+ }
4330 }
44-
45-
46- return time + bridge_length ;
31+
32+ return currentTime + bridge_length ;
4733 }
4834}
0 commit comments