프로그래머스 level2 다리를 지나는 트럭(큐)

하우르·2021년 3월 19일
0
post-custom-banner
import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
class Solution {
    
    static class Truck {
		int weight, second;

		public Truck(int n, int second) {
			this.weight = n;
			this.second = second;
		}
	}
	public static int Queue(int bridge_length, int weight, int[] truck_weights) {
		Queue<Truck> crossing_trucks = new LinkedList<Truck>();
		Queue<Integer> waiting_trucks = new LinkedList<Integer>();
		int current_weight = 0;
		for(int i=0; i<truck_weights.length; i++)
			waiting_trucks.add(truck_weights[i]);

		int second=0;
		while(true)
		{
			second++;
			if(!waiting_trucks.isEmpty())
			{
				if(current_weight+waiting_trucks.peek()<=weight) {
					current_weight+=waiting_trucks.peek();
					crossing_trucks.add(new Truck(waiting_trucks.remove(), second));

				}
			}

			if(!crossing_trucks.isEmpty())
			{
				if(second-crossing_trucks.peek().second==bridge_length-1)
				{
					current_weight-=crossing_trucks.remove().weight;
				}
			}
			if(waiting_trucks.isEmpty()&& crossing_trucks.isEmpty())
				return second+1;
		}

	}

    
    public int solution(int bridge_length, int weight, int[] truck_weights) {
        int answer = Queue(bridge_length,weight, truck_weights);

        return answer;
    }
}
profile
주니어 개발자
post-custom-banner

0개의 댓글