Under construction

Still being built. Things may change

Cross Country Skiing

Time limit1sMemory limit512 MB

Summary
Find the smallest elevation gap D that keeps every waypoint mutually reachable through adjacent cells.
Level

Medium5 of 10

Topics
Minimum spanning tree, Union-find, Sorting
Solved
No attempts yet

Problem

The cross-country skiing course at the winter Moolympics is described by an M×NM \times N grid of elevations (1≤M,N≤5001 \le M, N \le 500). Every elevation is an integer between 00 and 10910^9.

Some cells of the grid are marked as waypoints. The organizers want to give the whole course a difficulty rating DD so that a cow can get from any waypoint to any other waypoint by repeatedly skiing from a cell to an adjacent cell whose elevation differs by at most DD in absolute value. Two cells are adjacent when one is directly north, south, east, or west of the other. The difficulty rating of the course is the smallest DD for which all waypoints are mutually reachable.

If the course has fewer than two waypoints, the difficulty rating is 00.

Input

  • Line 1: the integers MM and NN.
  • Lines 2 to 1+M1+M: each line has NN integer elevations.
  • Lines 2+M2+M to 1+2M1+2M: each line has NN values, each either 00 or 11. A 11 marks a waypoint.

Output

  • Line 1: the difficulty rating of the course, the smallest DD that keeps every waypoint reachable from every other waypoint.

Hint

The first example describes a 3×53 \times 5 grid. The upper-left, upper-right, and lower-right cells are waypoints.

With D=21D = 21 the three waypoints reach each other. With any DD smaller than 2121, the upper-right waypoint cannot be reached from the other two.

Examples1

  1. Example 1

    Input
    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
    
    Expected output
    21