Official
F - Move Segment Editorial by en_translator
The answer is obtained by swapping the \(K\) 1
-block and the 0
-block right before that.
Thus, the problem can be solved by the following algorithm:
- Split the string by the boundaries of
0
and1
. - Swap the \(K\)-th
1
-block and the previous block. - Concatenate the string.
Sample input 1:
010011100011001 ↓ split 0 1 00 111 000 11 00 1 ↓ swap 0 1 00 111 11 000 00 1 ↓ join 010011111000001
Sample code (Python)
N,K = map(int,input().split())
S = input()
# split
idx = [0] + [i for i in range(1,N) if S[i-1]!=S[i]] + [N]
splited_S = [S[idx[i]:idx[i+1]] for i in range(len(idx)-1)]
# swap
if S[0] == '0':
kth_1_idx = 2*K-1
else:
kth_1_idx = 2*K-2
splited_S[kth_1_idx-1], splited_S[kth_1_idx] = splited_S[kth_1_idx], splited_S[kth_1_idx-1]
# join
T = "".join(splited_S)
print(T)
posted:
last update: