1. 문제

1431번: 시리얼 번호



2. 개요

각각의 고유한 시리얼 번호를 가진 기타들이 있다.

이 기타들을 아래의 조건에 맞게 정렬하려고 한다.

  1. A와 B의 길이가 다르면, 짧은 것이 먼저 온다.
  2. 만약 서로 길이가 같다면, A의 모든 자리수의 합과 B의 모든 자리수의 합을 비교해서 작은 합을 가지는 것이 먼저온다. (숫자인 것만 더한다)
  3. 만약 1,2번 둘 조건으로도 비교할 수 없으면, 사전순으로 비교한다. 숫자가 알파벳보다 사전순으로 작다.

주어진 시리얼 번호를 정렬하여 출력하는 문제.



3. 풀이 및 코드

3-1. 풀이

1, 3번은 단순히 주어진 문자열의 길이와 문자열의 값으로 정렬 조건에 추가하기만 하면 된다.

2의 경우 숫자인 경우에만 더해서 합을 구해야하기 때문에 따로 생각할 필요가 있다.

따라서 합을 저장해 둘 필요하므로, 시리얼 넘버를 key, 합을 value로 하는 딕셔너리를 만들어둔다.

시리얼 넘버를 받을 때마다 리스트에 해당 문자열을 넣어주면서 문자열의 모든 자릿수를 탐색하며 숫자라면 해당 딕셔너리의 값을 그만큼 늘려준다.

모든 시리얼 넘버를 입력받았다면 리스트를 조건에 맞는 순서로 정렬한 후 답을 출력한다.

3-2. Python

import sys

N = int(sys.stdin.readline())

sumdict = dict()
nums = []

for i in range(N):
    num = sys.stdin.readline().rstrip()
    nums.append(num)
    sumdict[num] = 0

    for j in range(len(num)):
        if num[j].isdigit():
            sumdict[num] += int(num[j])

    
nums.sort(key = lambda x : (len(x), sumdict[x], x))

for n in nums:
    print(n)

3-3. C#

namespace boj_1431
{
    internal class Program
    {
        static void Main(string[] args)
        {
            StreamReader sr = new StreamReader(Console.OpenStandardInput());
            StreamWriter sw = new StreamWriter(Console.OpenStandardOutput());

            Dictionary<string, int> sumdict = new Dictionary<string, int>();
            List<string> nums = new List<string>();

            int N = int.Parse(sr.ReadLine());

            for (int i = 0; i < N; i++)
            {
                string serial = sr.ReadLine().TrimEnd();
                sumdict[serial] = 0;
                nums.Add(serial);

                for (int j = 0; j < serial.Length; j++)
                {
                    if (char.IsDigit(serial[j]))
                        sumdict[serial] += int.Parse(serial[j].ToString());
                }
            }

            nums = nums.OrderBy(x => (x.Length, sumdict[x], x)).ToList();

            for (int i = 0; i < nums.Count; i++)
                sw.WriteLine(nums[i]);

            sw.Close();
        }
    }
}

Comments