atcoder#ABC289E. [ABC289E] Swap Places

[ABC289E] Swap Places

Score : 500500 points

Problem Statement

There is a simple undirected graph with NN vertices numbered 11 through NN and MM edges numbered 11 through MM. Edge ii connects vertex uiu_i and vertex viv_i. Every vertex is painted either red or blue. The color of vertex ii is represented by CiC_i; vertex ii is painted red if CiC_i is 00 and blue if CiC_i is 11.

Now, Takahashi is on vertex 11 and Aoki is on vertex NN. They may repeat the following move zero or more times.

  • Each of the two simultaneously moves to a vertex adjacent to the current vertex. Here, the vertices that Takahashi and Aoki move to must have different colors.

By repeating the move above, can Takahashi and Aoki simultaneously end up on vertices NN and 11, respectively? If it is possible, find the minimum number of moves required. If it is impossible, print -1.

You are given TT at the beginning of the input. Solve the problem for TT test cases.

Constraints

  • 1T10001 \leq T \leq 1000
  • 2N20002 \leq N \leq 2000
  • 1Mmin(N(N1)2,2000)1 \leq M \leq \min(\frac{N(N-1)}{2}, 2000)
  • Ci{0,1}C_i \in \lbrace 0, 1 \rbrace
  • 1ui,viN1 \leq u_i, v_i \leq N
  • The graph given in the input is simple.
  • All values in the input are integers.
  • The sum of NN over all test cases does not exceed 20002000.
  • The sum of MM over all test cases does not exceed 20002000.

Input

The input is given from Standard Input in the following format, where testi\text{test}_i denotes the ii-th test case:

TT

test1\text{test}_1

test2\text{test}_2

\vdots

testT\text{test}_T

Each test case is given in the following format:

NN MM

C1C_1 C2C_2 \dots CNC_N

u1u_1 v1v_1

u2u_2 v2v_2

\vdots

uMu_M vMv_M

Output

Print TT lines. The ii-th line should contain the answer to the ii-th test case. For each test case, print the minimum number of moves required for Takahashi and Aoki to simultaneously end up in vertices NN and 11, respectively, if it is possible, and -1 otherwise.

3
4 4
0 1 0 1
1 2
2 3
1 3
2 4
3 3
0 1 0
1 2
2 3
1 3
6 6
0 0 1 1 0 1
1 2
2 6
3 6
4 6
4 5
2 4
3
-1
3

For the 11-st test case, Takahashi and Aoki can achieve the objective by making the following 33 moves, which is the minimum number:

  • Takahashi moves to vertex 33, and Aoki moves to vertex 22.
  • Takahashi moves to vertex 22, and Aoki moves to vertex 33.
  • Takahashi moves to vertex 44, and Aoki moves to vertex 11.

Note that in the 11-st move, it is disallowed that both Takahashi and Aoki move to vertex 22 (because the colors of vertices that Takahashi and Aoki move to must be different.)

For the 22-nd case, no matter how they move, they cannot achieve the objective.