본문 바로가기

코딩 테스트/프로그래머스

프로그래머스 다리를 지나는 트럭 Java 풀이

기존 풀이

import java.util.*;

class Solution {
    public int solution(int bridge_length, int weight, int[] truck_weights) {
        int answer = 1;
        int tot_weight = 0;

        Queue<Truck> q = new LinkedList<Truck>();
        Queue<Truck> q2 = new LinkedList<Truck>();

        for (int i = 0 ; i < truck_weights.length ; i++) {
            q.offer(new Truck(bridge_length, truck_weights[i]));
        }

        tot_weight += q.peek().weight;
        q2.offer(q.poll());

        while (!q2.isEmpty()) {
            for(Truck truck : q2) {
                truck.time--;
            }

            if(q2.peek().time == 0) {
                tot_weight -= q2.poll().weight;
            }

            if(!q.isEmpty() && tot_weight + q.peek().weight <= weight) {
                tot_weight += q.peek().weight;
                q2.offer(q.poll());
            }
            answer++;
        }
        return answer;
    }
}

class Truck {
    int time;
    int weight;

    public Truck(int time, int weight) {
        this.time = time;
        this.weight = weight;
    }
}

https://dreamhollic.tistory.com/entry/%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98-%EB%AC%B8%EC%A0%9C%ED%92%80%EC%9D%B4-11-%EB%8B%A4%EB%A6%AC%EB%A5%BC-%EC%A7%80%EB%82%98%EB%8A%94-%ED%8A%B8%EB%9F%AD-JAVA 이 분의 풀이를 참고했다.

 

다른 사람의 풀이

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