Telephone

아직 제출이 없습니다시간 제한1초메모리 제한512 MB

문제

Farmer John's NN cows, conveniently numbered 1N1 \ldots N, are standing in a line (1N51041\le N\le 5\cdot 10^4). The iith cow has a breed identifier b_ib\_i in the range 1K1 \ldots K, with 1K501\le K\le 50. The cows need your help to figure out how to best transmit a message from cow 11 to cow NN.

It takes ij|i-j| time to transmit a message from cow ii to cow jj. However, not all breeds are willing to communicate with each other, as described by a K×KK \times K matrix SS, where S_ij=1S\_{ij} = 1 if a cow of breed ii is willing to transmit a message to a cow of breed jj, and 00 otherwise. It is not necessarily true that S_ij=S_jiS\_{ij}=S\_{ji}, and it may even be the case that S_ii=0S\_{ii} = 0 if cows of breed ii are unwilling to communicate with each-other.

Please determine the minimum amount of time needed to transmit the message.

입력

The first line contains NN and KK.

The next line contains NN space-separated integers b_1,b_2,,b_Nb\_1,b\_2,\ldots,b\_N.

The next KK lines describe the matrix SS. Each consists of a string of KK bits, S_ijS\_{ij} being the jjth bit of the iith string from the top.

출력

Print a single integer giving the minimum amount of time needed. If it is impossible to transmit the message from cow 11 to cow NN, then output 1-1.