[BOJ][C#] 13335 트럭

LimJaeJun·2023년 9월 19일
0

PS/BOJ

목록 보기
29/108

📕 문제

📌 문제 링크

📗 접근 방식

  1. 큐를 사용하여 다리 위에 있는 트럭을 관리
  2. 다리를 건너는 과정을 시뮬레이션하면서 시간을 측정
  3. 다음 트럭이 다리에 진입할 수 있는지 여부를 판단하고, 진입할 수 없다면 대기
  4. 모든 트럭이 다리를 건널 때까지 반복

📘 코드

using System;
using System.Collections.Generic;

namespace BOJ
{
    class No_13335
    {
        static void Main()
        {
            // 입력 받기
            var input = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
            int n = input[0]; // 트럭의 수
            int w = input[1]; // 다리의 길이
            int l = input[2]; // 다리의 최대하중

            int[] a = new int[n]; // 각 트럭의 무게
            input = Array.ConvertAll(Console.ReadLine().Split(), int.Parse);
            for (int i = 0; i < n; i++)
                a[i] = input[i];

            Queue<int> q = new Queue<int>();
            int ans = 0;
            int sum = 0;

            for (int i = 0; i < n; i++)
            {
                while (true)
                {
                    // 다리 위의 트럭 수가 다리의 길이를 초과하면 트럭을 빼내기
                    if (q.Count == w)
                        sum -= q.Dequeue();

                    // 다음 트럭이 다리에 진입 가능하면 진입
                    if (sum + a[i] <= l)
                        break;

                    // 대기하고 있는 트럭을 표시
                    q.Enqueue(0);
                    ans++;
                }

                // 다음 트럭을 다리에 진입시키고 무게 추가
                q.Enqueue(a[i]);
                sum += a[i];
                ans++;
            }

            // 모든 트럭이 다리를 건너는 시간에 대기 중인 트럭들의 시간 추가
            ans += w;
            Console.WriteLine(ans);
        }
    }
}

📙 오답노트

📒 알고리즘 분류

  • 구현
  • 자료 구조
  • 시뮬레이션
profile
Dreams Come True

0개의 댓글

관련 채용 정보