알고리즘 공부/프로그래머스

(Java)프로그래머스 코딩테스트 연습 - 스택/큐 - 다리를 지나는 트럭

HRuler 2020. 11. 12. 12:41

1. 문제

https://programmers.co.kr/learn/courses/30/lessons/42583?language=java

 

코딩테스트 연습 - 다리를 지나는 트럭

트럭 여러 대가 강을 가로지르는 일 차선 다리를 정해진 순으로 건너려 합니다. 모든 트럭이 다리를 건너려면 최소 몇 초가 걸리는지 알아내야 합니다. 트럭은 1초에 1만큼 움직이며, 다리 길이

programmers.co.kr

2. 나의 풀이

import java.util.*;

class Solution {
    public int solution(int bridge_length, int weight, int[] truck_weights) {
        int answer = 0;
    	
    	Queue <Integer> q = new LinkedList <Integer>();
    	
    	int mugae = 0;
    	for(int i : truck_weights) {
    		while(true) {
    			if(q.isEmpty()) {
    				q.offer(i);
    				mugae += i;
    				answer++;
    				break;
    			}else if(q.size() == bridge_length) {
    				mugae -= q.poll();
    			}else {
    				if(mugae + i > weight) {
    					q.offer(0);
    					answer++;
    				}else {
    					q.offer(i);
    					mugae += i;
    					answer++;
    					break;
    				}
    			}
    		}
    	}
    	
    	return answer + bridge_length;
    }
}

3. 다른 사람 풀이

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;
    }
}