This page is still under construction.

Parts of this page are still being built. What you see may change.

Telephone

Time limit1sMemory limit512 MB

Summary
Find the minimum total distance to pass a message from position 1 to position N, where a hop from i to j costs |i-j| and is allowed only when breed b_i can send to breed b_j.
Level

Medium7 of 10

Topics
Dynamic programming, Graph, Shortest path, Bit manipulation
Solved
No attempts yet

Problem

Farmer John's NN cows, numbered 1…N1 \ldots N, are standing in a line (1≤N≤5⋅1041\le N\le 5\cdot 10^4). The iith cow has breed identifier bib_i in the range 1…K1 \ldots K, with 1≤K≤501\le K\le 50. The cows want to determine the best way to transmit a message from cow 11 to cow NN.

Transmitting a message from cow ii to cow jj takes ∣i−j∣|i-j| time. Not all breeds are willing to communicate with each other, however, as described by a K×KK \times K matrix SS, where Sij=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 Sij=SjiS_{ij}=S_{ji}, and it may even be the case that Sii=0S_{ii} = 0 if cows of breed ii are unwilling to communicate with each other.

Determine the minimum amount of time needed to transmit the message.

Input

The first line contains NN and KK.

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

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

Output

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.

Examples1

  1. Example 1

    Input
    5 4
    1 4 2 3 4
    1010
    0001
    0110
    0100
    
    Expected output
    6