[BOJ][C#] 1092 배

LimJaeJun·2024년 1월 11일
0

PS/BOJ

목록 보기
95/108

📕 문제

📌 링크

📗 접근 방식

첫번째 코드

  • 크레인과 박스 리스트를 내림차순으로 정렬
  • 첫 번째 크레인이 첫 번째 박스보다 무겁지 않으면 모든 크레인이 해당 박스를 옮길 수 없으므로 -1을 출력하고 종료
  • CalculateRounds 함수를 호출하여 옮기는 최소 시간을 계산
    • 크레인부터 순회하며 탐색 => 한번 다 돌때 마다 카운팅
    • 해당 크레인으로 들 수 있는 가장 무거운 박스를 탐색
      • 들 수 있다면 해당 상자 리스트에서 해당 인덱스 제거
    • 결과적으로 몇번 돌았는지 최소 시간 반환
  • 결과를 출력

📘 코드

첫번째 코드

namespace BOJ
{
    class No_1092
    {
        static void Main()
        {
            int craneCount = InputToInt(); // 최대 50
            List<int> craneList = InputToList(); // 크레인 리스트
            int boxCount = InputToInt(); // 최대 10,000
            List<int> boxList = InputToList(); // 박스 리스트
            
            // 내림차순 정렬
            craneList.Sort(Comparer<int>.Create((x, y) => y - x));
            boxList.Sort(Comparer<int>.Create((x, y) => y - x));

            // 첫 요소 비교
            if (boxList.First() > craneList.First())
            {
                // 박스가 크레인보다 크면 옮길 수 없음
                Console.WriteLine("-1");
                return;
            }

            int answer = CalculateRounds(craneList, boxList);
            Console.WriteLine(answer);
        }
        
        /// <summary> 몇번 옮겨야 되는지 반환하는 함수 </summary>
        static int CalculateRounds(List<int> craneList, List<int> boxList)
        {
            // 총 옮기는 횟수
            int rounds = 0;

            while (boxList.Count > 0)
            {
                rounds++;

                for (int craneIndex = 0; craneIndex < craneList.Count; craneIndex++)
                {
                    int boxIndex = FindHeaviestBox(craneList[craneIndex], boxList);

                    if (boxIndex != -1)
                    {
                        boxList.RemoveAt(boxIndex);
                    }
                }
            }

            return rounds;
        }

        /// <summary> 해당 크레인으로 옮길 수 있는 최대 무게의 상자 인덱스 반환 </summary>
        static int FindHeaviestBox(int craneCapacity, List<int> boxList)
        {
            for (int i = 0; i < boxList.Count; i++)
            {
                if (craneCapacity >= boxList[i])
                {
                    return i;
                }
            }

            return -1;
        }
        
        static int InputToInt() => int.Parse(Console.ReadLine());
        static List<int> InputToList() => Array.ConvertAll(Console.ReadLine().Split(), int.Parse).ToList();
    }
}

두번째 코드

📙 오답노트

  1. 틀림
    => -1을 고려하지 않음

  2. ArgumentOutofRange Error, 시간 초과 => 반복문을 작성시 boxList.Count로 하지않고 boxCount로 입력해서 시간초과가 난 것같다. (boxList의 크기는 변화하지만 반복문에 적용하지 않음)

📒 알고리즘 분류

  • 그리디 알고리즘
  • 정렬
profile
Dreams Come True

0개의 댓글

관련 채용 정보