알고리즘/백준

[알고리즘/백준] 1431: 시리얼 번호

CodeHunst 2025. 5. 8. 18:34

https://www.acmicpc.net/problem/1431

 

 

 

 

 

1. 문제 접근

주어진 조건에 따라 시리얼 번호를 정렬해야 한다.

정렬 문제는 algorithm 라이브러리의 sort 함수를 이용하여 풀 수 있다.

 

  std::sort(A.begin(), A.end(), compare);

 

sort함수의 마지막 인자인 compare를 정의하여 문제를 해결한다.

 

2. 코드

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

int cmp(std::string aString, std::string bString)
{
    // 1.길이가 짧은 것이 먼저
    const int aSize = aString.size();
    const int bSize = bString.size();
    if (aSize != bSize)
    {
        return aSize < bSize;
    }
    // 2.숫자의 합이 작은 것이 먼저 
    int aSum = 0;
    int bSum = 0;
    for (const char& c : aString)
    {
        if (c >= '0' && c <= '9')
        {
            aSum += c - '0';
        }
    }
    for (const char& c : bString)
    {
        if (c >= '0' && c <= '9')
        {
            bSum += c - '0';
        }
    }
    if (aSum != bSum)
    {
        return aSum < bSum;
    }
    // 3.사전순
    return aString < bString;
}

int main()
{
    std::ios::sync_with_stdio(false);
    std::cin.tie(NULL);
    std::cout.tie(NULL);

    int N;
    std::cin >> N;
    std::vector<std::string> guitars(N);
    for (int i = 0; i < N; ++i)
    {
        std::cin >> guitars[i];
    }

    std::sort(guitars.begin(), guitars.end(), cmp);

    for (int i = 0; i < N; ++i)
    {
        std::cout << guitars[i] << "\n";
    }
}