Pictionary
Time limit1.5sMemory limit64 MB
Cities get roads on day i joining all pairs whose gcd is M-i+1; for each query, find the first day two given cities become connected.
- Level
Hard8 of 10
- Topics
- Union-find, Number theory, Graph, Math
- Solved
- No attempts yet
Problem
In an undiscovered corner of the universe there is a planet with a country where only mathematicians live. The country has mathematicians, and each one lives in a city of their own. The cities are numbered to . Mathematicians talk online or read each other's papers, so at the start no two cities are connected by a road.
Life was fine until one mathematician wrote a paper on a smartphone. Autocorrect changed the word "self-evident" to "Pictionary", and the paper was published that way. The whole country soon heard about Pictionary and wanted to meet and play, so construction of roads between the cities began.
The construction lasts days and follows this schedule. On the first day, roads are built between every pair of cities whose greatest common divisor is . On the second day, roads are built between every pair whose greatest common divisor is , and so on, until day , when roads are built between every pair of coprime cities. Formally, on day a road is built between cities and if .
Two mathematicians can meet once their cities can reach each other along roads, passing through other cities if needed. The mathematicians are busy with the construction, so they ask you for the minimum number of days after which a given pair can play Pictionary together.
Input
The first line contains three positive integers , , and (, ): the number of cities, the number of days the construction takes, and the number of queries.
Each of the next lines contains two distinct positive integers and (), the cities of the two mathematicians who want to know how many days it takes before they can play Pictionary together.
Output
Print lines. Line contains the minimum number of days after which the two mathematicians of query can play Pictionary together.
Hint
Explanation of the first sample. On day the road is built, so the answer to the second query is . On day the roads , , , , and are built, and cities and become connected through city . On day roads are built between coprime cities, so cities and become connected.
Explanation of the second sample. The road is built on day and the road on day . After day , cities and are connected through city .