Oversized Pancake Flipper (Large)
Time limit5sMemory limit512 MB
Given a row of happy or blank pancakes and a flipper of fixed width K, find the minimum number of flips that makes every pancake happy, or report that it is impossible.
- Level
Medium5 of 10
- Topics
- Greedy, Sliding window
- Solved
- No attempts yet
Problem
A pancake house introduced a new kind of pancake. One side has a happy face made of chocolate chips (the happy side), and the other side has nothing on it (the blank side).
You are the head cook on duty. The pancakes cook in a single row on a hot surface. To work faster, the house has bought an oversized pancake flipper that flips exactly consecutive pancakes at once. Inside that range of pancakes it turns every happy side up pancake blank side up and every blank side up pancake happy side up. It does not change the left to right order of the pancakes.
Raised borders run along both sides of the cooking surface, so you cannot flip fewer than pancakes at a time, not even at the ends of the row. For example, you can flip the leftmost pancakes, but not the leftmost pancakes.
Your apprentice cook, who is still learning the job, used the old single pancake flipper to turn over some individual pancakes and then walked off with it. Customers are about to visit the kitchen. The oversized flipper is the only tool left, and every pancake has to end up happy side up.
Given the current state of the pancakes, compute the minimum number of uses of the oversized pancake flipper that leaves every pancake happy side up, or report that no sequence of uses does it.
Input
The first line contains the number of test cases . Each of the next lines contains a string and an integer , separated by a space. describes the row of pancakes. Each of its characters is either +, a pancake that starts happy side up, or -, a pancake that starts blank side up.
Limits
- Every character of is either
+or-.
Output
For each test case, print one line in the form Case #x: y, where is the test case number starting from 1. is IMPOSSIBLE when no sequence of flips leaves every pancake happy side up, and otherwise the minimum number of times the oversized flipper has to be used.
Notes
When is ---+-++- and , flip the leftmost 3 pancakes to reach ++++-++-, then the rightmost 3 to reach ++++---+, then the 3 pancakes that are still blank side up. Other sequences also finish in 3 flips, and none finishes in 2 or fewer.
When is +++++ and , every pancake is already happy side up, so no flip is needed.
When is -+-+- and , every legal flip covers both the second and the third pancake from the left, so those two always turn together. They start on opposite sides, so they can never show the same side, and no sequence of flips leaves the whole row happy side up.