Modulo Solitaire

Time limit1sMemory limit128 MB

Summary
Given a modulus m, up to 10 affine maps, and a start s0, find the fewest moves to reach 0.
Level

Easy3 of 10

Topics
BFS, Graph
Solved
No attempts yet

Problem

Modulo Solitaire is a game you can play when you are bored, even on paper without a phone. First you pick a modulus mm. Then you pick nn pairs of numbers (ai,bi)(a_i, b_i). Finally you pick a starting number s0s_0. Your goal is to reach 00 from s0s_0 in as few moves as possible.

In each move you choose an index ii (with 1≤i≤n1 \le i \le n), then replace your current number ss by (s⋅ai+bi) mod m(s \cdot a_i + b_i) \bmod m. In other words, if sj−1s_{j-1} is your number just before the jj-th move and you choose index ii, then sj=(sj−1⋅ai+bi) mod ms_j = (s_{j-1} \cdot a_i + b_i) \bmod m.

Determine the smallest number of moves needed to turn s0s_0 into 00.

Input

The first line contains three integers mm, nn, and s0s_0 with 0<m≤1060 < m \le 10^6, 0≤n≤100 \le n \le 10, and 0<s0<m0 < s_0 < m.

Each of the next nn lines contains two integers aia_i and bib_i with 0≤ai≤1090 \le a_i \le 10^9 and 0≤bi≤1090 \le b_i \le 10^9.

Output

Output a single integer: the smallest number of moves needed to reach 00 starting from s0s_0. If 00 can never be reached, output −1-1.

Examples2

  1. Example 1

    Input
    5 2 1
    2 1
    3 1
    
    Expected output
    2
    
  2. Example 2

    Input
    10 0 5
    
    Expected output
    -1