CF BUDDY
← Problems·

1913E · Matrix Problem

2400 · flows, graphs

Problem: You are given a matrix aa, consisting of nn rows by mm columns. Each element of the matrix is equal to 00 or 11.

You can perform the following operation any number of times (possibly zero): choose an element of the matrix and replace it with either 00 or 11.

You are also given two arrays AA and BB (of length nn and mm respectively). After you perform the operations, the matrix should satisfy the following conditions:

  1. the number of ones in the ii-th row of the matrix should be exactly AiA_i for every i[1,n]i \in [1, n].
  2. the number of ones in the jj-th column of the matrix should be exactly BjB_j for every j[1,m]j \in [1, m].

Calculate the minimum number of operations you have to perform.

Input Format: The first line contains two integers nn and mm (2n,m502 \le n, m \le 50).

Then nn lines follow. The ii-th of them contains mm integers ai,1,ai,2,,ai,ma_{i,1}, a_{i,2}, \dots, a_{i,m} (0ai,j10 \le a_{i,j} \le 1).

The next line contains nn integers A1,A2,,AnA_1, A_2, \dots, A_n (0Aim0\le A_i\le m).

The next line contains mm integers B1,B2,,BmB_1, B_2, \dots, B_m (0Bin0\le B_i\le n).

Output Format: Print one integer — the minimum number of operations you have to perform, or -1 if it is impossible.

Sample Cases

Case 1

Input

3 3
0 0 0
0 0 0
0 0 0
1 1 1
1 1 1

Output

3

Case 2

Input

3 3
1 1 1
1 1 1
1 1 1
3 2 1
1 2 3

Output

3

Case 3

Input

2 2
0 0
0 0
1 2
0 1

Output

-1

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback