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 49 50 51 52 53 54 | #include <stdio.h> #include <string.h> char arr[100001] = { 0 }; int num[100001]; void qSort(int left, int right) { int l = left + 1, r = right, pivot = num[left]; do { while (num[l] <= pivot && l < right) l++; while (pivot <= num[r] && left < r) r--; if (l < r) { int temp = num[l]; num[l] = num[r]; num[r] = temp; } } while (l < r); int temp = num[left]; num[left] = num[r]; num[r] = temp; if (left < r - 1) qSort(left, r - 1); if (r + 1 < right) qSort(r + 1, right); } int main() { scanf("%s", arr); int len = strlen(arr); for (int i = 0; i < len; i++) { num[i] = (int)arr[i]-48; } qSort(0, len - 1); int numSum = 0, flag = 0; for (int i = 0; i < len; i++) { numSum += num[i]; if (num[i] == 0) flag = 1; } if (numSum % 3 != 0 || flag==0) { printf("-1"); return 0; } for (int i = len - 1; i >= 0; i--) { printf("%d", num[i]); } } | cs |
알고리즘/그리디 알고리즘