Divisor Roads
Time limit2sMemory limit512 MB
A one-way road runs from X to Y when some A_i divides X and B_i divides Y; find the shortest distance from S to T.
- Level
Hard8 of 10
- Topics
- Graph, BFS, Math, Number theory
- Solved
- No attempts yet
Problem
A country has N cities numbered from 1 to N. Some pairs of cities are joined by a one way road of length 1. The distance from city X to city Y is the smallest number of roads on a walk that starts at X and ends at Y.
Two sequences A and B of length M determine the road network. A one way road runs from X to Y if and only if at least one index i satisfies both conditions, that divides X and that divides Y.
For example, with , , and there are 7 cities and the roads are 2 -> 3, 2 -> 6, 4 -> 3, 4 -> 6, 6 -> 3, 6 -> 6.
Given two integers S and T, write a program that computes the distance from S to T.
Input
The first line contains N, S, T and M. (, , )
The second line contains the sequence A and the third line contains the sequence B. () The same pair is never given more than once.
Output
Print the distance from S to T on the first line. Print -1 if T cannot be reached from S.
Hint
In the first example the roads are (3, 5), (3, 10), (6, 5), (6, 10), (9, 5), (9, 10), (10, 2), (10, 4), (10, 6), (10, 8), (10, 10). The shortest walk from city 9 to city 6 is 9 -> 10 -> 6.
In the second example the first element of A and the first element of B are both 1, so a road runs between every pair of cities.
The shortest walk in the fourth example is 10 -> 56 -> 26 -> 34 -> 62.