


The initial satisfaction of a person of type A is 80. It decreases by 20 for each neighbor.
The initial satisfaction of a person of type B is 50. It increases by 10 for each neighbor.
You may choose exactly how many people you want to be present in the grid.
The total number of people of type ‘A’ living in the grid can be less than ‘countA’ but cannot exceed ‘countA’. Similarly, total number of people of type ‘B’ living in the grid can be less than ‘countB’ but cannot exceed ‘countB’
A person can live in only one cell.
Not more than one person can live in a cell.
Two cells are said to be neighbors if the cells are adjacent and share a boundary.
The first line contains an integer ‘T’, which denotes the number of test cases to be run. Then, the ‘T’ test cases follow.
The first and the only line of each test case contains four space-separated integers ‘N’, ‘M’, ‘countA’, and ‘countB’, denoting the grid’s dimensions and the number of each type of people present.
For each test case, print in a new line an integer denoting the maximum possible grid satisfaction.
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 2
1 <= N,M <= 6
0 <= countA, countB <= min(N*M, 6)
Time Limit: 1sec
The approach is to use Recursion along with Bitmasking. We can observe that we only need to know the last M cells we processed. We should only consider the cells at the top and left of the current cell because the right direction will be covered by someone else's left position, and the bottom position will be covered by someone else's top position. If a cell is filled, its contribution is fixed. If a neighbor cell is filled later, then the contribution of the original cell can be calculated towards the neighbor cell only.
The approach is to use Dynamic Programming along with Bitmasking. We can observe that we only need to know the last M cells we processed. We should only consider the cells at the top and left of the current cell because the right direction will be covered by someone else's left position, and the bottom position will be covered by someone else's top position. If a cell is filled, its contribution is fixed. If a neighbor cell is filled later, then the contribution of the original cell can be calculated towards the neighbor cell only. We can optimize our solution by storing the values for smaller subproblems in an array so that we don’t require to calculate the answer for the same subproblems again.