Computer Science/알고리즘

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

토마토. 2023. 4. 15. 15:46

코딩테스트 연습 - 다리를 지나는 트럭 | 프로그래머스 스쿨 (programmers.co.kr)

import java.util.*;

class Pair {
    int truck;
    int index;

    Pair(int truck, int index){
        this.truck = truck;
        this.index = index;
    }
}
class Solution {
    public static void print(Queue<Pair> queue){
        for (Pair p : queue){
            System.out.print(p.truck + " ");
        }
        System.out.println();
    }
    public static int solution(int bridge_length, int weight, int[] truck_weights){
        Queue<Pair> queue = new LinkedList<>();

        int answer = 0;
        int tmp_weight = 0;
        for (int i=0;i<bridge_length;i++){
            queue.add(new Pair(0, 0));
        }

        int index = 0;

        while (true){
            // print(queue);
            Pair poll_ = queue.poll();
            if (poll_ == null || poll_.index == truck_weights.length){
                break;
            }
            answer++;
            tmp_weight -= poll_.truck;

            if (index < truck_weights.length){
                if (tmp_weight + truck_weights[index] > weight){
                    queue.add(new Pair(0, 0));
                } else {
                    queue.add(new Pair(truck_weights[index], index));
                    tmp_weight += truck_weights[index];
                    index++;
                }
            }
        }
        // System.out.println(answer);
        return answer;
    }
}