Grid of Many Xors
Practice
4.6 (15 votes)
Algorithms
Graphs
Medium
Minimum spanning tree
Problem
61% Success 943 Attempts 30 Points 2s Time Limit 256MB Memory 1024 KB Max Code

Consider a grid with N rows and M columns, where each cell has some integer value written in it. Every cell is connected to every side adjacent cell via an undirected edge. The cost of an edge e connecting any two cells with value a and b is \(C_e = a \oplus b\). (Here \(\oplus\) denotes bitwise xor of two the integers a and b)

We define a good trip between two cells \((r_1, c_1)\) and \((r_2, c_2)\) as a trip starting at cell \((r_1, c_1)\) and ending at cell \((r_2, c_2)\) while visiting every cell of the grid at least once.

There is a cost associated with every good trip. Let's say, for a given edge e, you travel that edge \(T_e\) times. Then the cost of the trip is:

\( \displaystyle\sum_{ \forall e}{\Bigg( C_e * \Biggl\lceil \frac{T_e}{2} \Biggr\rceil\Bigg)} \)

Here, \(\Big\lceil \frac{T_e}{2} \Big\rceil\) is the ceiling of the result of division of \(T_e\) by 2

For the given starting cell \((r_1, c_1)\) and ending cell \((r_2, c_2)\), you have to find the minimum cost of a good trip.

Input Format

The first line will consist of the integer T denoting the number of test cases.

For each of the T test cases, the first line will consist of two integers N and M, denoting the number of rows and columns of the grid respectively.

The second line will consist of four integers, \(r_1 c_1 r_2 c_2\), denoting the coordinates \((r_1, c_1)\) of the starting cell and \((r_2, c_2)\) of the ending cell.

Then, N lines will follow, each containing M integers, denoting the values in the grid, such that the \(j^{th}\) value in the \(i^{th}\) row will denote the number in the cell \((i, j)\) of the grid.

Output Format

For each of the T test cases, output a single integer, denoting the minimum cost of a good trip.

Constraints

\( 1 \le T \le 10 \)

\( 1 \le N \times M \le 10^5 \)

\( 1 \le r_1, r_2 \le N \)

\( 1 \le c_1, c_2 \le M \)

\( 1 \le Grid(i, j) \le 10^4 \)

where \(Grid(i, j)\) denotes the integer in the given grid at cell \((i, j)\).

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:30
64 votes
Tags:
ApprovedGraphsGreedy AlgorithmsKruskal's AlgorithmMediumMinimum spanning treeOpen
Points:30
32 votes
Tags:
AlgorithmsBit ManipulationGraphsMediumMinimum spanning tree
Points:30
5 votes
Tags:
GraphsAlgorithmsMinimum Spanning Tree