Examples [code] [code] ----- [code] [code] ----- [code] [code]
- User
Examples
5 1 BGGBGGBGGB
5 2 BGGBGGGBGB
4 1 GGGBGGGB Assistant
5 1
BGGBG
GBGGB
5 2
BGGBG
GGBGB
4 1
GGGB
GGGB
First, I need to understand what's being asked: ## Examples
5 1
BGGBG
GBGGB
5 2
BGGBG
GGBGB
4 1
GGGB
GGGB
Key values given: 5, 1, 5, 2, 4, 1
My approach:
This models boys and girls in a queue where boys can move forward past girls, one position per time unit.
Algorithm
For each
2. position
Else:
i = i + 1
Verification with Examples
Example 1: n=5, t=1, s="BGGBG"
Start: B G G B G
i=0: B,G → swap → G B G B G, skip to i=2
i=2: G,B → no swap, i=3
i=3:
3. position after swap
else:
i += 1
print(''.join(s))
solve()
Time Complexity: O(T × N)
Space Complexity: O(N)
This gives us the final answer: "GBGGB" ✓
Looking at this problem, I need to understand the transformation pattern from the examples.
Let me trace through each example to identify the pattern:
BGGBG → GBGGB (T=1)BG → GB (swapped)GB → no swap (wrong order)BG → GB (swapped)BGGBG → GGBGB (T=2)After T=1: GBGGB
BG → GB (swapped)After T=2: GGBGB ✓
GGGB → GGGB (T=1)BG pairs found, no swapsThe transformation rule is:
B is immediately followed by G, swap them to GBThis models boys and girls in a queue where boys can move forward past girls, one position per time unit.
For each of T iterations:
i = 0
While i < n-1:
If s[i] = 'B' and s[i+1] = 'G':
Swap s[i] and s[i+1]
i = i + 2 // Skip next position
Else:
i = i + 1
Example 1: n=5, t=1, s="BGGBG"
Start: B G G B G
i=0: B,G → swap → G B G B G, skip to i=2
i=2: G,B → no swap, i=3
i=3: B,G → swap → G B G G B, done
Result: "GBGGB" ✓
Example 2: n=5, t=2, s="BGGBG"
After t=1: G B G G B (as above)
After t=2:
i=0: G,B → no swap, i=1
i=1: B,G → swap → G G B G B, done
Result: "GGBGB" ✓
Example 3: n=4, t=1, s="GGGB"
i=0: G,G → no swap
i=1: G,G → no swap
i=2: G,B → no swap
Result: "GGGB" ✓
def solve():
n, t = map(int, input().split())
s = list(input().strip())
for _ in range(t):
i = 0
while i < n - 1:
if s[i] == 'B' and s[i + 1] == 'G':
s[i], s[i + 1] = s[i + 1], s[i]
i += 2 # Skip next position after swap
else:
i += 1
print(''.join(s))
solve()
Time Complexity: O(T × N)
Space Complexity: O(N)