|
| 1 | +```java |
| 2 | +import java.io.BufferedReader; |
| 3 | +import java.io.IOException; |
| 4 | +import java.io.InputStreamReader; |
| 5 | + |
| 6 | +public class Main { |
| 7 | + |
| 8 | + static int len; |
| 9 | + static int[] arr,numCnt,eraseCnt; |
| 10 | + static String ans; |
| 11 | + |
| 12 | + public static void main(String[] args) throws IOException { |
| 13 | + init(); |
| 14 | + process(); |
| 15 | + print(); |
| 16 | + } |
| 17 | + private static void init() throws IOException{ |
| 18 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 19 | + |
| 20 | + String input = br.readLine(); |
| 21 | + len = input.length(); |
| 22 | + arr = new int[len]; |
| 23 | + |
| 24 | + numCnt = new int[10]; |
| 25 | + for (int i = 0; i < len; i++) { |
| 26 | + arr[i] = input.charAt(i) - '0'; |
| 27 | + numCnt[arr[i]]++; |
| 28 | + } |
| 29 | + |
| 30 | + String erase = br.readLine(); |
| 31 | + eraseCnt = new int[10]; |
| 32 | + for (int i = 0; i < erase.length(); i++) { |
| 33 | + eraseCnt[erase.charAt(i) - '0']++; |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + private static void process() { |
| 38 | + // 남을 숫자 개수 |
| 39 | + int[] remaining = new int[10]; |
| 40 | + int totalRemain = 0; |
| 41 | + for (int i = 0; i < 10; i++) { |
| 42 | + remaining[i] = numCnt[i] - eraseCnt[i]; |
| 43 | + totalRemain += remaining[i]; |
| 44 | + } |
| 45 | + |
| 46 | + // suffix count 전처리 |
| 47 | + int[][] suffixCnt = new int[len + 1][10]; |
| 48 | + for (int i = len - 1; i >= 0; i--) { |
| 49 | + for (int d = 0; d < 10; d++) { |
| 50 | + suffixCnt[i][d] = suffixCnt[i + 1][d]; |
| 51 | + } |
| 52 | + suffixCnt[i][arr[i]]++; |
| 53 | + } |
| 54 | + |
| 55 | + StringBuilder sb = new StringBuilder(); |
| 56 | + int pos = 0; |
| 57 | + |
| 58 | + // 결과 길이만큼 반복 |
| 59 | + for (int resultPos = 0; resultPos < totalRemain; resultPos++) { |
| 60 | + // 가장 큰 숫자부터 시도 |
| 61 | + for (int num = 9; num >= 0; num--) { |
| 62 | + if (remaining[num] == 0) continue; |
| 63 | + |
| 64 | + // 원본에서 num을 찾기 |
| 65 | + boolean found = false; |
| 66 | + for (int i = pos; i < len; i++) { |
| 67 | + if (arr[i] == num) { |
| 68 | + // 이 num을 선택했을 때, i+1부터 나머지를 만들 수 있는지 확인 |
| 69 | + remaining[num]--; |
| 70 | + |
| 71 | + boolean canMake = true; |
| 72 | + for (int d = 0; d < 10; d++) { |
| 73 | + if (suffixCnt[i + 1][d] < remaining[d]) { |
| 74 | + canMake = false; |
| 75 | + break; |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + if (canMake) { |
| 80 | + sb.append(num); |
| 81 | + pos = i + 1; |
| 82 | + found = true; |
| 83 | + break; |
| 84 | + } else { |
| 85 | + remaining[num]++; |
| 86 | + } |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + if (found) break; |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + ans = sb.toString(); |
| 95 | + } |
| 96 | + |
| 97 | + |
| 98 | + |
| 99 | + private static void print() { |
| 100 | + System.out.println(ans); |
| 101 | + } |
| 102 | +} |
| 103 | +``` |
0 commit comments