Codeforces Round #531 (Div. 3) D Balanced Ternary String【模拟】

You are given a string ss consisting of exactly nn characters, and each character is either '0', '1' or '2'. Such strings are called ternary strings.
Your task is to replace minimum number of characters in this string with other characters to obtain a balanced ternary string (balancedternary 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').
Among all possible balanced ternary strings you have to obtain the lexicographically (alphabetically) smallest.
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'.
It is guaranteed that the answer exists.
Input
The first line of the input contains one integer nn (3≤n≤3?1053≤n≤3?105, nn is divisible by 33) — the number of characters in ss.
The second line contains the string ss consisting of exactly nn characters '0', '1' and '2'.
Output
Print one string — the lexicographically (alphabetically) smallest balanced ternary string which can be obtained from the given one with minimum number of replacements.
Because nn is divisible by 33 it is obvious that the answer exists. And it is obvious that there is only one possible answer.
Examples
input
Copy

3 121

output
Copy
021

input
Copy
6 000000

output
Copy
001122

input
Copy
6 211200

output
Copy
211200

input
【Codeforces Round #531 (Div. 3) D Balanced Ternary String【模拟】】Copy
6 120110

output
Copy
120120

a = int(input()) s = str(input()) z = 0 o = 0 t = 0 for i in s: if i == '0': z += 1 if i == '1': o += 1 if i == '2': t += 1 num = a // 3 zn = num - z on = num - o tn = num - t if z == o == t: print(s) else: zm = 0 om = 0 tm = 0 s = list(s) for i in range(0, a): if s[i] == '2': if tn < 0: if zn > 0: s[i] = '0' zn -= 1 tn += 1 else: s[i] = '1' on -= 1 tn += 1 if s[i] == '1': om += 1 if on < 0: if zn > 0: s[i] = '0' zn -= 1 on += 1 om -= 1 else: if om <= num: continue else: s[i] = '2' tn -= 1 on += 1 if s[i] == '0': zm += 1 if zn < 0: if zm <= num: continue else: if on > 0: on -= 1 s[i] = '1' zn += 1 else: s[i] = '2' tn -= 1 zn += 1 s = ''.join(s) print(s)


    推荐阅读