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";
}
}'알고리즘 > 백준' 카테고리의 다른 글
| [알고리즘/백준] 1766: 문제집 (1) | 2025.07.11 |
|---|---|
| [알고리즘/백준] 9251: LCS (1) | 2025.07.08 |
| [알고리즘/백준] 4195: 친구 네트워크 (0) | 2025.07.08 |
| [알고리즘/백준] 12847: 꿀 아르바이트 (0) | 2025.05.17 |
| [알고리즘/백준] 20922: 겹치는 건 싫어 (0) | 2025.05.10 |