https://school.programmers.co.kr/learn/courses/30/lessons/42583
import java.util.Queue;
import java.util.LinkedList;
class Solution {
public int solution(int bridge_length, int weight, int[] truck_weights) {
int answer = 0;
int totalWeight = 0;
Queue<Integer> que = new LinkedList<>();
for (int truck : truck_weights) {
while (true) {
// 1. que가 비어있을 떄 (= 다리 위에 트럭이 없을 때)
if (que.isEmpty()) {
que.offer(truck);
totalWeight += truck;
answer++;
break;
}
// 2. que가 비어있지 않을 때 (= 다리 위에 트럭이 있을 때)
else {
// 2-1) que가 가득 찼을 때 (= 다리 길이만큼 트럭이 올라와있을 때)
if (que.size() == bridge_length) {
totalWeight -= que.poll();
} // 2-2) 다음 트럭을 올렸을 때 최대 무게 초과할 때
else if (totalWeight + truck > weight) {
que.offer(0);
answer++;
} else {
// 2-3) 다음 트럭이 최대무게 이내일 때
que.offer(truck);
totalWeight += truck;
answer++;
break;
}
}
}
}
return answer + bridge_length;
}
}
import java.util.*;
class Solution {
public int solution(int bridge_length, int weight, int[] truck_weights) {
int answer = 0;
Queue<Integer> bridge = new LinkedList<>();
// 비어있는 다리의 공간을 0으로 채움.
for(int i=0;i<bridge_length;i++){
bridge.offer(0);
}
int index = 0;
int currentWeight = 0; // 다리위에 있는 트럭의 무게
while(index < truck_weights.length){
// 나갈 트럭의 무게 빼줌
currentWeight -= bridge.poll();
answer++; // 새 트럭이 들어올 것이므로 1초를 추가
if(currentWeight + truck_weights[index] <= weight){
// 다리에 트럭 추가
bridge.offer(truck_weights[index]);
currentWeight += truck_weights[index++];
} else{
// 무거우면 0추가
bridge.offer(0);
}
}
//처음 설정한 0으로 채워진 다리가 전부 치환되면 결국 처음 다리 길이와 같으므로
//트럭이 지나간 시간 + 다리 길이
return answer + 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;
}
}
오지고 지리는 객체지향적 설계
너무 어려웠다. 감탄만하다 갑니다..
큐!
큐의 개념은 아는데 응용하는게 어려웠던 문제였다.
혼자서 어떻게든 풀겠다 아등바등 했는데 3시간이 훌쩍 지나있었고 결국 풀지 못했다 훌쩍..
다른 사람 풀이를 참고해서 코드를 짯는데 잘 모르겠어서 여러번 봐야 될 것 같다.
하지만 배운점이 있다면
1. 어떤 기준으로 분기처리를 할 것인지
2. 경우를 어떻게 심플하게 나눌 수 있는지 생각하기
후.. 처음엔 큐를 안쓰고 어떻게 풀 수 있을지 이리저리 써봤는데 분기처리랑 반복문 해결하는 부분이 잘 안됐다. 그 코드 다시 써봐야지..