-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSolution.java
49 lines (40 loc) ยท 1.84 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package dev.idion.programmers.truckpassingbridge;
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
public int solution(int bridgeLength, int weight, int[] truckWeights) {
int time = 0;
int totalWeight = 0;
Queue<Truck> bridge = new LinkedList<>();
Queue<Truck> truckQueue = new LinkedList<>();
// ๋๊ธฐ์ด(Queue)์ truck ์ถ๊ฐ
for (int truckWeight : truckWeights) {
truckQueue.offer(new Truck(truckWeight, 0));
}
while (!truckQueue.isEmpty() || !bridge.isEmpty()) {
time++; // ์ง์
์๊ฐ (๋ฃจํ ๋ง๋ค 1์ด์ฉ ์งํ๋๋ค.)
// ๋ค๋ฆฌ๊ฐ ๋น์ด์์ง ์๊ณ , ํ์ฌ์๊ฐ - ๋ค๋ฆฌ์ ์ง์
ํ ์๊ฐ์ด ๋ค๋ฆฌ์ ๊ธธ์ด๋ณด๋ค ํฌ๊ฑฐ๋ ๊ฐ๋ค๋ฉด(์ง๋๊ฐ๋ค๋ฉด)
// ๋ค๋ฆฌ์์ ํธ๋ญ์ ๊บผ๋ด๊ณ ๋ค๋ฆฌ์ ๋ฌด๊ฒ์์ ํธ๋ญ์ ๋ฌด๊ฒ๋ฅผ ๋บ๋ค.
if (!bridge.isEmpty() && time - bridge.peek().entryTime >= bridgeLength) {
totalWeight -= bridge.poll().weight;
}
// ๋๊ธฐ์ด์ด ์๊ณ , ์ ํ ๋ฌด๊ฒ๋ณด๋ค ๋ค๋ฆฌ์์ ๋ฌด๊ฒ + ์ฌ๋ผ๊ฐ ํธ๋ญ์ ๋ฌด๊ฒ๊ฐ ์ ๋ค๋ฉด...
// ๋๊ธฐ์ด์์ ํธ๋ญ์ ๊บผ๋ด์ ๋ค๋ฆฌ์์ ๋ฌด๊ฒ์ ๋ํ ํ, ์ง์
์์ ์ ์๊ฐ์ ์ ์ฅํ๊ณ ๋ค๋ฆฌ์ ์ฌ๋ฆฐ๋ค.
if (!truckQueue.isEmpty() && totalWeight + truckQueue.peek().weight <= weight) {
Truck truck = truckQueue.poll();
totalWeight += truck.weight;
truck.entryTime = time;
bridge.offer(truck);
}
}
return time;
}
private static class Truck {
private int weight;
private int entryTime;
public Truck(int weight, int entryTime) {
this.weight = weight;
this.entryTime = entryTime;
}
}
}