Azugand (En)
Azugand (En)
Andrei, a well-known child from the valley, wants to make a table with the shortest distances between
two points of interest, but he is overwhelmed by the number of queries he wants to solve, so he asks for
your help! You are given Q queries, in which you have to compute cost(X, Y ). We define cost(X, Y ) as
the minimum number of edges that are in the shortest path in the graph between vertices X and Y . If
we can’t reach vertex Y from vertex X, then the value of cost(X, Y ) is −1.
Input
The first line of input contains two integers N and Q, the number of vertices in the graph, and the
number of queries, respectively.
The next line contains N integers V1 , V2 , . . . , VN , the values assigned to the vertices of the graph.
Each of the next Q lines of the input contains two distinct integers Xi and Yi , the vertices for which you
must compute cost(Xi , Yi ).
azugand Page 1 of 3
Output
Print Q integers, each one on a separate line: the value of cost(Xi , Yi ) for each query.
Constraints
• 1 ≤ N ≤ 200 000.
• 1 ≤ Q ≤ 200 000.
• 0 ≤ Vi < 220 for each i = 1 . . . N .
• 1 ≤ Xi ̸= Yi ≤ N for each i = 1 . . . Q.
Scoring
Your program will be tested against several test cases grouped in subtasks. In order to obtain the score
of a subtask, your program needs to correctly solve all of its test cases.
– Subtask 1 (0 points) Examples.
– Subtask 2 (16 points) N ≤ 500, Q ≤ 500.
– Subtask 3 (25 points) Q ≤ 1.
– Subtask 4 (24 points) Vi < 25 for each i = 1 . . . N .
– Subtask 5 (35 points) No additional limitations.
Examples
input output
4 4 1
9 3 16 6 1
1 2 2
2 4 -1
4 1
2 3
7 5 5
3072 5120 67584 73728 49152 24576 2
40960 3
2 5 1
7 3 4
1 6
5 6
7 2
azugand Page 2 of 3
Explanation
In the first sample case:
• In the first query V1 = 9 and V2 = 3, 9&3 = 1, so there is an edge between vertices 1 and 2, so the
minimum distance is 1.
• In the second query V2 = 3 and V4 = 6, 3&6 = 2, so there is an edge between vertices 2 and 4, so
the minimum distance is 1.
• In the third query V4 = 6 and V1 = 9, 6&9 = 0, so there is no edge between vertices 4 and 1, so the
minimum distance is at least 2. For the path 4, 2, 1 the values are 6, 3, 9 respectively which means
that there is an edge between vertices 4 and 2 also between 2 and 1, so there is a path of length 2
between vertices 4 and 1.
• In the fourth query V1 &V3 = 0, V2 &V3 = 0 and V4 &V3 = 0, which means that there are no edges
connected to vertex 3, so there is no path between vertices 2 and 3.
azugand Page 3 of 3