참고
문제해설
문제 로직고민
NOTE
•
Queue 방식처럼 FIFO를 사용하는건 맞는데 몇가지 제약조건이 있다.
◦
내부에서 1칸씩 트럭이 움직여야하고, 범위를 벗어나면 사라진다.
◦
내부에 있는 트럭의 무게 총합이 기준치를 넘어서면 안된다.
◦
위의 제약조건 때문에 int[]을 사용해서 Queue와 비슷하게 구현한다.
작성코드
NOTE
class Solution {
public int solution(int bridge_length, int weight, int[] truck_weights) {
Queue queue = new Queue(bridge_length, weight);
int answer = queue.offer(truck_weights);
return answer;
}
}
class Queue {
int[] queue;
int maxWeight;
int curWeight;
public Queue(int size, int weight){
this.queue = new int[size];
this.maxWeight = weight;
this.curWeight = 0;
}
public int offer(int[] trucks){
int cnt = 0;
for(int i =0; i<trucks.length; i++){
int weight = trucks[i];
// 다리에 차가 올라갈 수 있는가? (못올라가면 도로에 있는 차만 움직임)
if(curWeight + weight > maxWeight) {
i--;
move(0);
}
// 올라갈 수 있으면, 차량추가하고 움직임
else {
move(weight);
}
cnt++;
}
return cnt + queue.length;
}
// 차가 움직인다 (0 -> 1, 1 -> 2 ...)
public void move(int weight){
for(int i =queue.length-2; i >= 0; i--){
queue[i+1] = queue[i];
}
// 처음값은 무조건 새로온 트럭이거나 0
queue[0] = weight;
curWeight = curWeight - queue[queue.length-1] + weight;
}
}
Java
복사
•
풀이 시간 : 16분
다른사람 풀이
NOTE
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;
}
}
Java
복사
깔끔하게 작성한 코드