cswork / OAOpen practice workspace

MicrosoftOA #51

Minimum Swaps Required to Group All Red Balls Together

Estimated MediumJudge-ready

Topics (AI-labelled)GreedyPrefix & Ranges

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.

Input

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

Output a single integer, the answer.

Example 1

Input:

WRRWR

Output:

1

Example 2

Input:

WWRWWWWWWWWWRWR

Output:

10

Example 3

Input:

WWW

Output:

0

Example notes

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.

Editorial

Loading solution…