Fancy Formulas
Time limit2sMemory limit512 MB
Given a prime p and pairs (a,b) with a+b not divisible by p, find the minimum number of operations to transform one pair into another, or report impossibility.
- Level
Hard8 of 10
- Topics
- Math, Number theory, Graph, BFS
- Solved
- No attempts yet
Problem
You are given a prime and a pair of integers such that their sum is not divisible by . In one operation, you can do one of the following:
- Replace with
- Replace with
You have to answer queries. In the -th query, find the smallest number of operations needed to transform the pair into the pair , or determine that it is impossible.
Note that the order of numbers matters. For example, for , the distance between and is , not .
Input
The first line contains two integers and (, is prime, ): the prime and the number of queries to answer.
The -th of the next lines contains four integers , , , (, and is not divisible by ).
Output
For each query, if it is impossible to transform into , output . Otherwise, output the smallest number of operations required to achieve this goal.