Modulo Solitaire
Time limit1sMemory limit128 MB
Given a modulus m, up to 10 affine maps, and a start s0, find the fewest moves to reach 0.
Problem
Modulo Solitaire is a game you can play when you are bored, even on paper without a phone. First you pick a modulus . Then you pick pairs of numbers . Finally you pick a starting number . Your goal is to reach from in as few moves as possible.
In each move you choose an index (with ), then replace your current number by . In other words, if is your number just before the -th move and you choose index , then .
Determine the smallest number of moves needed to turn into .
Input
The first line contains three integers , , and with , , and .
Each of the next lines contains two integers and with and .
Output
Output a single integer: the smallest number of moves needed to reach starting from . If can never be reached, output .