Reachability Precomputation on Jump Graph With Weighted Cost (final boss graph problem)
EXTREME · C · 5000ms
Finally, combining ideas: in the failover network, some large "safe-hub" machines allow free jumps, and Lamia needs the minimum total cost to reach a backup machine from any starting point, given this mix of free and costly jumps. Extend the SHA75-style jump graph: from index i you may move to i+A[i] or i-A[i], but EACH move costs 1 unit, UNLESS you move to an index that is a multiple of a given value M, in which case that specific move costs 0. Answer Q queries of (start, end): print the minimum cost to go from start to end, or -1 if unreachable. Use 0-1 BFS (deque-based) since edge weights are only 0 or 1.
Input
Line1: N M. Line2: N integers (array A). Line3: Q. Next Q lines: start end.
Output
Q lines: minimum cost, or -1.
Constraints
1 ≤ N ≤ 10^5, 1 ≤ Q ≤ 1000
Sample Input
5 2 2 3 1 1 1 1 1 5
Sample Output
1
Write C, then Run (custom I/O) or Submit (sample tests). ⌘/Ctrl+Enter submits.