Wormly
Time limit1sMemory limit128 MB
Find the minimum number of moves to shift a worm's body window and its ordered legs across a bridge with missing planks, or report impossibility.
- Level
Hard8 of 10
- Topics
- Greedy, Two pointers, Simulation
- Solved
- No attempts yet
Problem
Jonly is making his first computer game. In the opening scene the hero, Wormly, has to cross the bridge Bridgely.
Wormly is a worm made of identical round bubbles and legs. At every instant each leg must be directly below one of the bubbles, and each bubble may have at most one leg below it. The bubbles touch one another, so the bubbles always cover consecutive planks.
Bridgely consists of planks, each as wide as one bubble, but some planks are missing. A leg may rest only on an existing plank, never on a gap.
At each step Wormly performs exactly one of the following actions:
- Move one leg forward over any number of planks (existing or missing). After the move the leg must rest on an existing plank that lies below one of the bubbles. A leg may never pass another leg, so the legs keep their left-to-right order.
- Move every bubble forward by one plank while all legs stay on their current planks. After this move each leg must still be below some bubble.
Initially the bubbles cover the leftmost planks and the legs rest on the leftmost planks. The animation ends when the bubbles cover the rightmost planks and the legs rest on the rightmost planks. The leftmost planks and the rightmost planks are guaranteed to exist.
Determine the minimum number of steps Wormly needs to cross, counting both leg moves and bubble moves, or report that crossing is impossible.
Input
The first line contains a positive integer , the number of test cases (). Each test case consists of two lines:
- A line with three integers , and (): the number of legs, the number of bubbles, and the number of planks.
- A line with a string of characters, each either
1or0. A1marks an existing plank and a0marks a missing plank.
Output
For each test case output a single line with one integer: the minimum number of steps Wormly needs to cross the bridge. If crossing is impossible, output IMPOSSIBLE instead.