Telephone
Time limit1sMemory limit512 MB
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 cows, numbered , are standing in a line (). The th cow has breed identifier in the range , with . The cows want to determine the best way to transmit a message from cow to cow .
Transmitting a message from cow to cow takes time. Not all breeds are willing to communicate with each other, however, as described by a matrix , where if a cow of breed is willing to transmit a message to a cow of breed , and otherwise. It is not necessarily true that , and it may even be the case that if cows of breed are unwilling to communicate with each other.
Determine the minimum amount of time needed to transmit the message.
Input
The first line contains and .
The next line contains space-separated integers .
The next lines describe the matrix . Each consists of a string of bits, being the th bit of the th 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 to cow , then output .