Under construction

Still being built. Things may change

Matrix Game

Interview

Time limit1sMemory limit2048 MB

Summary
For each column, pick the row that maximizes |a - b| there, then sum those maxima over all M columns Chan calls to get the largest possible Diff.
Level

Easy2 of 10

Topics
Array, Implementation
Solved
No attempts yet

Problem

Hun and Chan are playing a matrix game. Each has an N×NN \times N matrix, A=(aij)A = (a_{ij}) and B=(bij)B = (b_{ij}).

The game has MM rounds. In each round, Hun and Chan call out the numbers α\alpha and β\beta at the same time. Here α\alpha and β\beta are integers between 1 and NN. Hun scores aαβa_{\alpha\beta} points and Chan scores bαβb_{\alpha\beta} points.

Last night Hun dreamed the MM numbers β1,β2,…,βM\beta_1, \beta_2, \dots, \beta_M that Chan will call in the rounds. Hun can therefore choose MM numbers α1,α2,…,αM\alpha_1, \alpha_2, \dots, \alpha_M that maximize Diff. Diff is defined as ∑k=1M∣aαkβk−bαkβk∣\sum_{k=1}^M \left| a_{\alpha_k \beta_k} - b_{\alpha_k \beta_k} \right|, the sum over all rounds of the absolute difference between the two players' scores in that round.

Given the MM numbers Chan calls in each round, write a program that outputs the maximum possible value of Diff when Hun chooses his MM numbers to maximize it.

Input

The first line contains two integers NN and MM (1≤N≤1,0001 \le N \le 1,000, 1≤M≤1,000,0001 \le M \le 1,000,000). NN is the size of each player's matrix, and MM is the number of rounds.

The next NN lines contain Hun's matrix AA, where line ii holds the NN values of row ii. The following NN lines contain Chan's matrix BB in the same way. All matrix values are integers between 0 and 1,000.

The last line contains MM integers between 1 and NN, the numbers Chan calls in each round.

Output

Print the maximum value of Diff when Hun chooses his MM numbers to maximize it.

Examples2

  1. Example 1

    Input
    2 2
    1 2
    0 1
    3 1
    2 1
    2 1
    
    Expected output
    3
    
  2. Example 2

    Input
    2 3
    5 0
    2 6
    3 3
    3 2
    1 1 2
    
    Expected output
    8