Intruder Outsmarting
InterviewTime limit5sMemory limit1024 MB
Each wheel moves by plus or minus D on a cycle of N numbers. Find the fewest turns that make the wheel values a palindrome, or report that it is impossible.
- Level
Medium5 of 10
- Topics
- Number theory, Math, Implementation
- Solved
- No attempts yet
Problem
The security key has wheels in a row. Each wheel has the numbers through printed in order. One rotation moves the number shown on a wheel to the next or the previous number. Numbers wrap around, so the number after is , and the number before is .
There is no hidden password. To activate the key, the numbers shown must form a palindrome, meaning the sequence reads the same from left to right and from right to left. To slow down intruders, the wheels only turn in steps of . In one operation, a wheel showing can be changed to show or . The wraparound works like this: if , the number shown becomes , and if , the number shown becomes .
Given the current number on each wheel, find the minimum number of operations needed to make the sequence of shown numbers a palindrome, or report that it is impossible.
Input
The first line contains the number of test cases . Each test case consists of two lines. The first line has three integers , , and . The second line has integers , where is the number currently shown on the -th wheel from the left.
Output
For each test case, output one line containing Case #x: y, where is the test case number starting from 1, and is the minimum number of operations needed to make the shown sequence a palindrome. If it is impossible, output IMPOSSIBLE instead of .
Limits
- .
- .
- , for all .
Hint
In Sample Case #1, the sequence can be made , which is a palindrome, with operations: one addition on the first and fourth wheels, and one subtraction on the fifth wheel. No sequence of fewer moves works.
In Sample Case #2, the sequence is already a palindrome, so no operations are needed.
In Sample Case #3, both numbers must be equal for the sequence to be a palindrome. The wheel values only move by , and the two current numbers have different parity, so this cannot be done.