Under construction

Still being built. Things may change

City

Time limit4sMemory limit1024 MB

Summary
Given an N by N grid of developed and undeveloped regions with tourism values, pick K undeveloped regions to develop so the total value of the resulting cities is maximized.
Level

Medium7 of 10

Topics
Graph, Dynamic programming, Matrix
Solved
No attempts yet

Problem

A square country is a grid of N×NN \times N square regions. A map marks each region as 11 if it is developed and 00 if it is not. A region is a city if it is developed and all four regions adjacent to it (up, down, left, and right) are also developed. A region on the edge cannot be a city.

Each region has a tourism value. If the cell in row ii, column jj becomes a city, its tourism value is VijV_{ij}. Otherwise, its tourism value is 00.

The country has capital to develop KK more regions. The country is not wealthy, so KK is always less than or equal to the number of undeveloped regions. To maximize tourism revenue, find the maximum possible sum of tourism values of the cities after developing KK new regions.

Input

The first line contains NN and KK, separated by a space.

From the second line onward, the next NN lines describe the map. Line ii contains Mi1,Mi2,⋯ ,MiNM_{i1}, M_{i2}, \cdots, M_{iN}, separated by spaces. If MijM_{ij} is 11, the cell in row ii, column jj is already developed. If MijM_{ij} is 00, it is not.

From line N+2N+2 onward, the next NN lines contain the tourism values. Line ii contains Vi1,Vi2,⋯ ,ViNV_{i1}, V_{i2}, \cdots, V_{iN}, separated by spaces.

Output

Print the maximum sum of tourism values of the cities after developing KK regions.

Constraints

  • All given numbers are integers.
  • 3≤N≤123 \leq N \leq 12
  • 0≤K≤500 \leq K \leq 50
  • Mij∈{0,1}M_{ij} \in \{0, 1\} (1≤i,j≤N1 \le i,j \le N)
  • 0≤Vij≤1 000 0000 \leq V_{ij} \leq 1\,000\,000 (1≤i,j≤N1 \le i,j \le N)
  • KK is always less than or equal to the number of undeveloped regions.

Examples2

  1. Example 1

    Input
    4 3
    0 0 1 0
    0 1 0 0
    0 0 0 0
    1 0 0 0
    29 67 78 70
    65 58 98 43
    43 11 91 88
    68 45 77 58
    
    Expected output
    98
    
  2. Example 2

    Input
    5 1
    1 1 1 1 1
    1 1 1 1 1
    1 1 0 1 1
    1 1 1 1 1
    1 1 1 1 1
    1 2 3 4 5
    5 4 3 2 1
    1 2 3 4 5
    5 4 3 2 1
    1 2 3 4 5
    
    Expected output
    27