#P7243. 最大公约数

    ID: 5859 远端评测题 2000ms 500MiB 尝试: 0 已通过: 0 难度: 5 上传者: 标签>模拟搜索数学O2优化广度优先搜索,BFS

最大公约数

Description

On the contrary, social circles come in all kinds of shapes, and the common divisors are pitifully small. It seems hard to keep one’s own personality, and thus one becomes a boring person.

Now abstract interpersonal relationships into an n×mn \times m rectangle. Each person’s initial personality is ai,ja_{i,j}. Starting from the second day, each person will build relationships with the four people up, down, left, and right (if they exist), and their personality becomes the greatest common divisor of their own personality yesterday and the personalities of the surrounding people. Then, for the person at row xx and column yy, after how many days will their personality become 11?


Simplified statement

There is an n×mn \times m matrix aa. Define one transformation on a matrix as: change every element in the matrix into the greatest common divisor of itself and its four adjacent elements (up, down, left, right; ignore non-existing ones). Ask for the minimum number of transformations needed for ax,ya_{x,y} to become 11. If ax,ya_{x,y} can become 11 after some number of transformations, output the minimum number; otherwise output 1-1.

Input Format

The first line contains two integers n,mn, m, indicating the number of rows and columns of the matrix.

The next nn lines each contain mm integers. The integer ai,ja_{i,j} in row ii and column jj describes the initial personality of the person at that position.

The next line contains two integers x,yx, y, indicating the position of a specified person.

Output Format

Output one integer dd, meaning that the personality of the person at row xx and column yy will become 11 after dd days. In particular, if it will never become 11, output 1-1.

2 2
2 2
1 2
2 1
0
2 2
2 2 
2 2
1 1
-1
3 3
3 2 3
2 3 2
3 2 3
2 2
1

Hint

Sample explanation 3

The personality matrix on the first day (i.e. the initial matrix) is

$$\begin{pmatrix} 3&2&3\\ 2&3&2\\ 3&2&3 \end{pmatrix}$$

The personality matrix on the second day is

$$\begin{pmatrix} 1&1&1\\ 1&1&1\\ 1&1&1 \end{pmatrix}$$

It can be seen that after only one day, a2,2a_{2,2} becomes 11, so the answer is 11.

Constraints and conventions

This problem uses bundled tests.

For 100%100\% of the testdata, 1n,m2×1031\le n,m\le 2\times 10^3, 1ai,j10181\le a_{i,j}\le 10^{18}, 1xn1\le x\le n, 1ym1\le y\le m.

Subtask Score n,mn,m Special constraints
1 1 / Guarantee that the personality at the given position will never become 11
2 Guarantee that ax,y=1a_{x,y}=1
3 2 \le 2 /
4 10 102 \le 10^2
5 30 5×102 \le 5\times 10^2
6 10 / Guarantee that for all ai,j2a_{i,j} \le 2
7 Guarantee that both xx and yy equal 11
8 35 /

Translated by ChatGPT 5