This page is still under construction.

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

Ski Course Rating

Time limit1sMemory limit128 MB

Summary
From each marked start cell, find the smallest elevation-step limit that connects it to at least T cells.
Level

Medium7 of 10

Topics
Union-find, Sorting, Graph
Solved
No attempts yet

Problem

The cross-country skiing course at the winter Moolympics is given as an M×NM \times N grid of elevations, with 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 starting points of the course. The organizers want to give each starting point a difficulty rating. The difficulty rating of a starting point PP is the smallest DD such that a cow who starts at PP reaches at least TT cells in total, counting PP itself, when she may only step between adjacent cells whose elevations differ by at most DD. Here 1≤T≤MN1 \le T \le MN. Two cells are adjacent when one lies directly north, south, east, or west of the other.

Compute the difficulty rating of every starting point and help the organizers.

Input

  • Line 1: the integers MM, NN, and TT.
  • Lines 22 to 1+M1 + M: each line holds NN integer elevations.
  • Lines 2+M2 + M to 1+2M1 + 2M: each line holds NN values, each of them 00 or 11. A 11 marks a cell that is a starting point.

Output

  • Line 1: the sum of the difficulty ratings of all starting points. A single rating fits in a 32-bit integer, but the sum may not.

Hint

Input details

The ski course is a 3×53 \times 5 grid of elevations. The upper-left cell and the lower-right cell are starting points, and from each starting point the cow must reach at least 1010 cells.

Output details

The difficulty rating of the upper-left starting point is 44, and the rating of the lower-right starting point is 2020.

Examples1

  1. Example 1

    Input
    3 5 10
    20 21 18 99 5
    19 22 20 16 17
    18 17 40 60 80
    1 0 0 0 0
    0 0 0 0 0
    0 0 0 0 1
    
    Expected output
    24