MicrosoftOA #51
Minimum Swaps Required to Group All Red Balls Together
估计中等可在线判题
Each step swaps two adjacent balls. Make all R form one contiguous block, with W allowed on both sides. Find the minimum number of swaps; if it exceeds 10⁹, output −1. The source's example swap sequences changed the number of balls, so this site corrected them according to the explicit adjacent-swap rule.
This site uses a standard input/output protocol.
输入格式
One line containing an R/W string. The source's range says 1..100000, but the statement explicitly requires a test with RW repeated 100000 times; this site keeps that case and supports lengths 1..200000.
输出格式
Output a single integer, the answer.
样例 1
输入:
WRRWR
输出:
1
样例 2
输入:
WWRWWWWWWWWWRWR
输出:
10
样例 3
输入:
WWW
输出:
0
样例说明
Example 1: swapping the final WR gives WRRRW in just 1 step; the source's answer of 2 has been corrected. Example 2: the red balls are at 2, 12, 14, and moving them to 11, 12, 13 takes 9+0+1=10 steps; the source's answer of 4 has been corrected. Example 3: there are no red balls, so 0 steps.