Checksum
Memory limit1024 MB
Given a partially corrupted N x N boolean matrix, its row and column XOR checksums, and recovery costs, find the minimum cost to reconstruct the matrix.
- Level
Medium5 of 10
- Topics
- Graph, Union-find, Greedy, Implementation
- Solved
- No attempts yet
Problem
Grace and Edsger are constructing an boolean matrix . The element in the -th row and -th column is written . They decide to note down the checksum (defined as the bitwise XOR of the given list of elements) along each row and each column. The checksum of the -th row is written , and the checksum of the -th column is written .
For example, if and , then and .
Once they finish the matrix, Edsger stores it on his computer. Due to a virus, some elements of matrix are replaced with on Edsger's computer. Luckily, Edsger still remembers the checksum values. He wants to restore the matrix and asks Grace for help. After some investigation, it turns out that recovering the original value of from the disk takes Grace hours. Given the final matrix , the cost matrix , and the checksums along each row () and column (), can you help Grace decide the minimum total number of hours needed to restore the original matrix ?
Input
The first line of the input gives the number of test cases, . test cases follow.
The first line of each test case contains a single integer .
The next lines each contain integers representing the matrix . The -th element on the -th line is .
The next lines each contain integers representing the matrix . The -th element on the -th line is .
The next line contains integers representing the checksums of the rows. The -th element is .
The next line contains integers representing the checksums of the columns. The -th element is .
Output
For each test case, output one line containing Case #x: y, where is the test case number (starting from 1) and is the minimum number of hours to restore matrix .
Constraints
- .
- , for all , .
- for , where , and otherwise.
- , for all .
- , for all .
- There is at least one way to replace the entries in with or so that and are satisfied.
Hint
In Sample Case #1, can be restored using the checksum of either the 1st row or the 2nd column. So Grace can restore the matrix without spending any time recovering data.
In Sample Case #2, Grace spends one hour to recover . After that, she can use the checksums of the 1st row and the 1st column to restore and respectively. Then she can use the checksum of the 2nd row to restore . So Grace can restore the matrix by spending one hour.
In Sample Case #3, Grace can spend one hour to recover and another hour to recover . After that, she can use the checksums to restore the rest of the matrix. So Grace can restore the matrix by spending two hours in total.