Face the Right Way
InterviewTime limit1sMemory limit128 MB
Choose a fixed block size K so that flipping blocks of K consecutive cows turns the whole row forward using the fewest operations, breaking ties by smallest K.
- Level
Medium6 of 10
- Topics
- Greedy, Simulation, Prefix sum, Brute force
- Solved
- No attempts yet
Problem
Farmer John has lined up his () cows in a row. Some cows face forward, but the rest face backward, and Farmer John wants every cow to face forward.
He owns an automatic cow-flipping machine. Because he bought the discount model, the machine is permanently preset to a single value (): every time it is used, it reverses the facing direction of some consecutive cows. A forward cow becomes backward and a backward cow becomes forward, while every cow stays in its original position. The machine can never act on fewer than cows, so it can only be applied to a block of exactly cows that lies entirely within the row.
Farmer John must commit to one fixed value of before he starts. Help him choose so that the machine can make all cows face forward using as few operations as possible, and let be that minimum number of operations for the chosen . If several values of allow the same minimum , choose the smallest such .
Input
- Line : a single integer .
- Lines : line contains a single character,
ForB, indicating whether cow faces forward (F) or backward (B).
Output
Print two space-separated integers and : the chosen value of (the one that minimizes the number of operations, and the smallest among ties) and the corresponding minimum number of operations .
Hint
Consider seven cows facing backward, backward, forward, backward, forward, backward, backward.
With the machine must be used three times — on cows , then , then — after which every cow faces forward. The diagram below traces each cow's direction as the three operations are applied; > marks a cow about to be flipped.
B > F F F
B > F F F
F > B > F F
B B > F F
F F > B > F
B B B > F
B B B > F
No fixed can finish this row in fewer than three operations, so the answer is and .