#P2658. 汽车拉力比赛

汽车拉力比赛

Description

Bo'ai City is going to hold a car rally.

The course is uneven, so it is represented by an M×NM \times N grid of elevations (1M,N500)(1 \leq M, N \leq 500). The elevation of each cell is between 00 and 10910^9.

Some cells are designated as checkpoints. The organizers want to assign a difficulty coefficient DD to the entire course such that, for any two checkpoints, there exists a path between them where the elevation difference between any pair of adjacent cells on that path does not exceed DD. In other words, DD is the minimum value that ensures all checkpoints are mutually reachable. Each cell is adjacent to the four cells to its north, south, east, and west.

Input Format

The first line contains two integers MM and NN.

Lines 22 through M+1M+1: each line contains NN integers giving the elevations.

Lines M+2M+2 through 2M+12M+1: each line contains NN integers, each either 00 or 11; 11 indicates that the cell is a checkpoint.

Output Format

Output a single integer, the difficulty coefficient DD.

3 5 
20 21 18 99 5  
19 22 20 16 26
18 17 40 60 80
1 0 0 0 1
0 0 0 0 0
0 0 0 0 1
21

Hint

Translated by ChatGPT 5