-
[c++] 백준 1431번 - 시리얼 번호Programming/알고리즘 문제 2020. 11. 7. 00:59
문자열의 수 N을 먼저 입력하고, N만큼 문자열을 입력한다.
1. 길이가 짧은 것
2. 길이가 같다면, 각 자리의 합이 작은것(숫자만 더할 것)
3. 각 자리의 합 또한 같다면 사전 순으로..
위의 세가지 조건을 만족시켜 c++ STL의 sort를 사용하여 정렬한다.
sort의 세번째 인자에는 compare 함수가 들어가며, compare 외에도 각 자리의 숫자의 합을 반환하는 integer_sum이라는 함수를 따로 구현하였다.
#include <iostream> #include <algorithm> #include <string> using namespace std; int n; string a[1000]; int integer_sum(string a) { int len = a.length(); int sum = 0; for (int i = 0; i < len; i++) { if (a[i] - '0' <= 9 && a[i] - '0' >= 0) { sum += a[i] - '0'; } } return sum; } bool compare(string a, string b) { if (a.length() < b.length()) { return 1; } else if (a.length() > b.length()) { return 0; } else { int sum_a = integer_sum(a); int sum_b = integer_sum(b); if (sum_a < sum_b) { return 1; } else if (sum_a > sum_b) { return 0; } else { return a < b; } } } int main() { cin >> n; for (int i = 0; i < n; i++) { cin >> a[i]; } sort(a, a + n, compare); for (int i = 0; i <n; i++) { cout << a[i] << ' '<<endl; } }
'Programming > 알고리즘 문제' 카테고리의 다른 글
[c++] 백준 2133번 - 타일 채우기 (0) 2020.11.15 [c++] 백준 11726번 - 2*n 타일링 (0) 2020.11.07 [c++] 백준 10989번 - 수 정렬하기 3 (0) 2020.11.07 [c++] 백준 1181번 - 단어 정렬 (0) 2020.11.07