Under construction

Still being built. Things may change

Base Defense

Time limit1sMemory limit1024 MB

Summary
Given F formations and each day's fixed last formation, find the minimum total squared-difference fatigue over L days of T changes each.
Level

Medium7 of 10

Topics
Dynamic programming, Matrix, Shortest path
Solved
No attempts yet

Problem

Starting today, the training period lasts LL days. Every day, the unit members must demonstrate formations selected from the base defense formation catalog.

For the training, FF formations are selected from the catalog and numbered 1 to FF. Formation xx is written C[x]C[x] (1≤x≤F1 \le x \le F). Each formation is an N×MN \times M grid matching the training site. C[x]ijC[x]_{ij} is the cell in row ii and column jj of C[x]C[x], equal to 1 if a soldier must stand in that cell and 0 otherwise. C[1]C[1] satisfies C[1]ij=0C[1]_{ij} = 0 for all ii, jj (1≤i≤N1 \le i \le N, 1≤j≤M1 \le j \le M).

On the first day, the routine starts from C[1]C[1]. From the second day on, each day starts from the last formation of the previous day. Until the day ends, TT more formations are demonstrated.

Each change of formation adds fatigue. If the formation being demonstrated is C[A]C[A] and the next one is C[B]C[B], the fatigue added is the square of the number of pairs (i,j)(i, j) where C[A]ijC[A]_{ij} and C[B]ijC[B]_{ij} differ (1≤i≤N1 \le i \le N, 1≤j≤M1 \le j \le M).

The last formation of each day is already fixed. The chief sergeant ordered the lead soldier to fill the remaining demonstrations with the selected formations so that the total fatigue is minimized. Find the total fatigue of that routine.

Input

The first line contains FF, LL, TT, NN, and MM, separated by spaces.

From the second line on, the information for C[1],C[2],⋯ ,C[F]C[1], C[2], \cdots, C[F] is given in order, using F×NF \times N lines in total. Each formation takes NN lines with MM values separated by spaces. The jj-th value on the ii-th line is C[x]ijC[x]_{ij}, and each value is 0 or 1.

Finally, the numbers l1,l2,⋯ ,lLl_1, l_2, \cdots, l_L of the formation to be demonstrated last on day 1 through day LL are given, separated by spaces.

Output

Print the total fatigue of the routine that minimizes fatigue on the first line.

Constraints

  • 2≤F≤502 \le F \le 50
  • 1≤L≤1 000 0001 \le L \le 1\,000\,000
  • 1≤T≤1 000 0001 \le T \le 1\,000\,000
  • 1≤N,M≤501 \le N, M \le 50
  • 1≤lk≤F1 \le l_k \le F (1≤k≤L1 \le k \le L)
  • For all ii, jj (1≤i≤N1 \le i \le N, 1≤j≤M1 \le j \le M), C[1]ij=0C[1]_{ij} = 0

Examples2

  1. Example 1

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

    Input
    3 5 1 2 2
    0 0
    0 0
    0 1
    0 0
    0 1
    1 0
    3 2 1 3 1
    
    Expected output
    14