#P7297. [USACO21JAN] Telephone G

[USACO21JAN] Telephone G

Description

Farmer John has NN cows, numbered 1N1 \ldots N, standing in a line (1N51041 \le N \le 5 \cdot 10^4). The breed ID of cow ii is bib_i, in the range 1K1 \ldots K, where 1K501 \le K \le 50. The cows need your help to find the best way to transmit a message from cow 11 to cow NN.

Transmitting a message from cow ii to cow jj takes time ij|i-j|. However, not all breeds of cows are willing to talk to each other, as described by a K×KK \times K matrix SS. If a cow of breed ii is willing to transmit a message to a cow of breed jj, then Sij=1S_{ij}=1, otherwise it is 00. It is not guaranteed that Sij=SjiS_{ij}=S_{ji}, and it is possible that Sii=0S_{ii}=0 if cows of breed ii are not willing to communicate with each other.

Find the minimum time required to transmit the message.

Input Format

The first line contains NN and KK.

The next line contains NN space-separated integers b1,b2,,bNb_1,b_2,\dots,b_N.

The following KK lines describe the matrix SS. Each line contains a string of KK binary digits. For the ii-th string from top to bottom, its jj-th character is SijS_{ij}.

Output Format

Output one integer, the minimum time required. If it is impossible to transmit the message from cow 11 to cow NN, output 1-1.

5 4
1 4 2 3 4
1010
0001
0110
0100
6

Hint

The optimal transmission sequence is 14351 \to 4 \to 3 \to 5. The total time is 14+43+35=6|1-4|+|4-3|+|3-5|=6.

Test Point Properties:

  • Test points 1-5 satisfy N1000N \le 1000.
  • Test points 6-13 have no additional constraints.

Problem provided by: Dhruv Rohatgi

Translated by ChatGPT 5