1102D.md (1818B)
1 Source: https://codeforces.com/problemset/problem/1102/D 2 3 D. Balanced Ternary String 4 5 time limit per test 6 7 2 seconds 8 9 memory limit per test 10 11 256 megabytes 12 13 input 14 15 standard input 16 17 output 18 19 standard output 20 21 You are given a string $s$ consisting of exactly $n$ characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings. 22 23 Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balanced ternary string is a ternary string such that the number of characters '0' in this string is equal to the number of characters '1', and the number of characters '1' (and '0' obviously) is equal to the number of characters '2'). 24 25 Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest. 26 27 Note that you can neither remove characters from the string nor add characters to the string. Also note that you can replace the given characters only with characters '0', '1' and '2'. 28 29 It is guaranteed that the answer exists. 30 31 Input 32 33 The first line of the input contains one integer $n$ ($3 \le n \le 3 \cdot 10^5$, $n$ is divisible by $3$) — the number of characters in $s$. 34 35 The second line contains the string $s$ consisting of exactly $n$ characters '0', '1' and '2'. 36 37 Output 38 39 Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements. 40 41 Because $n$ is divisible by $3$ it is obvious that the answer exists. And it is obvious that there is only one possible answer. 42 43 Examples 44 45 Input 46 47 ``` 48 3 49 121 50 ``` 51 52 Output 53 54 ``` 55 021 56 ``` 57 58 Input 59 60 ``` 61 6 62 000000 63 ``` 64 65 Output 66 67 ``` 68 001122 69 ``` 70 71 Input 72 73 ``` 74 6 75 211200 76 ``` 77 78 Output 79 80 ``` 81 211200 82 ``` 83 84 Input 85 86 ``` 87 6 88 120110 89 ``` 90 91 Output 92 93 ``` 94 120120 95 ```