Rescue Cricketer

0

0 votes
Brute Force, Flow, Medium-Hard
Problem

We all know that Raina is a great cricketer. However Due to some black magic he has lost his playing ability. So captain of team warned him to either play well or loose spot in the team. Fortunately he has some magic spell received by his grandfather. To activate the spell, he has to solve following problem.

You are given an array A of length N where Ai[1,L]. You are also given an array B of length N where Bi[1,L]. Also W[P][Q] denotes cost required to replace value P at any index i in the array A with value Q. Your task is to convert array A into array B by applying below two operations non negative number of times.

  • Swap the values of Ai and Aj for some i,j [1,N] with cost 0.
  • Choose any index i such that i[1,N] and update Ai=C where C[1,L] with cost W[Ai][C].

Assume that for integer P[1,L] you have used cost W[P][1], X1 times, W[P][2], X2 times, .. W[P][L], XL times, then the below condition should hold true for all values of P : Li=1XiK

He hired you to solve this task, can you help him find the minimum cost required to carry out this task?

Input format

First line contains single integer T representing number of test cases.
Each test case starts with three space separated integers, N, L and K.
Next line contains N space separated integers, ith of which denotes Ai.
Next line contains N space separated integers, ith of which denotes Bi.
Next L lines contains L space separated integers, jth integer in the ith line denotes W[i][j].

Output format

For each test case, print the required answer in a single line. If it's impossible to convert array A into array B, print 1 instead.

Constraints

1T5
1N105
1L100
0K104
1W[i][j]104 for ij
W[i][i]=0

Subtask Points
1N,L,K8 10%
W[i][j]=1  i,j[1,L] and ij
K=N
20%
Original Constraints 70%
Sample Input
2
5 2 0
1 2 1 2 2
1 1 2 2 2
0 1
1 0
5 3 1
1 2 2 2 2
2 2 2 2 2
0 10 1
10 0 10
10 1 0
Sample Output
0
2
Time Limit: 2
Memory Limit: 256
Source Limit:
Explanation

For the first test case, swap A2 and A3 with 0 cost. So the answer is 0.

For the second test case, we need to change A1 to 2, first change A1 to 3 with cost 1 (W[1][3], now you cannot use W[1][2] and W[1][1] and W[1][3] as K=1) and then change A1 to 2 with cost 1 (W[3][2], now you cannot use cost W[3][1] and W[3][2] and W[3][3] as K=1). So the minimum cost required is 2.

Editor Image

?