2017. 6. 26. 14:23
프로그래밍/알고리즘
그리디 알고리즘을 연습하기 위해서 찾은 문제다.
30의 배수
- 3의 배수 : 모든 자릿수의 합이 3의 배수가 되면 된다.
- 10의 배수 : 1의 자리 수가 0이면 된다.
위의 조건을 만족하는 상황에서 가장 큰 수를 만들면 된다. 가장 큰 수는 주어진 수들을 내림차순 정렬함으로써 얻을 수 있다.
Ex. 2931 -> 9321
코드는 3의 배수인지를 확인하고 내림차순 정렬한 후 끝자리가 0인지를 확인하는 것으로 끝난다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | // https://www.acmicpc.net/problem/10610 // [2017-06-26] 14시 05분 #include <iostream> #include <stdlib.h> #include <cstring> using namespace std; bool check(char buff[], size_t len) { unsigned int total = 0; for (int i = 0; i < len; i++) total += buff[i] - '0'; if (total % 3 == 0) return true; else return false; } int compare(const void *pCh1, const void *pCh2) { char ch1 = *(char *)pCh1; char ch2 = *(char *)pCh2; if (ch1 > ch2) return -1; else if (ch1 < ch2) return 1; else if (ch1 == ch2) return 0; } int main() { char buff[100001]; size_t buffLen; cin >> buff; buffLen = strlen(buff); if (!check(buff, buffLen)) cout << -1 << endl; else { qsort(buff, buffLen, sizeof(char), compare); if (buff[buffLen - 1] != '0') cout << -1 << endl; else cout << buff << endl; } return 0; } | cs |
가장 큰 수를 앞자리로 가져오는 것이 그리디 알고리즘인거 같다.
'프로그래밍 > 알고리즘' 카테고리의 다른 글
탐욕 알고리즘 (0) | 2020.01.11 |
---|---|
완전 탐색 (0) | 2020.01.11 |
[프로젝트 오일러] Prob4, Prob5 Prob9, Prob10 (0) | 2017.05.20 |
[프로젝트 오일러] Prob18 (0) | 2017.05.20 |
[프로젝트 오일러] Prob96 (스도쿠) (3) | 2017.04.09 |