You work in a company which organizes marriages. Marriages are not that easy to be made, so, the job is quite hard for you.
The job gets more difficult when people come here and give their bio-data with their preference about opposite gender. Some give priorities to family background, some give priorities to education, etc.
Now your company is in a danger and you want to save your company from this financial crisis by arranging as much marriages as possible. So, you collect N bio-data of men and N bio-data of women. After analyzing quite a lot you calculated the priority index of each pair of men and women.
Finally you want to arrange N marriage ceremonies, such that the total priority index is maximized. Remember that each man should be paired with a woman and only monogamous families should be formed.
Input
Input starts with an integer T (≤ 100), denoting the number of test cases.
Each case contains an integer N (1 ≤ n ≤ 16), denoting the number of men or women. Each of the next N lines will contain N integers each. The jth integer in the ithline denotes the priority index between the ith man and jth woman. All the integers will be positive and not greater than 10000.
Output
For each case, print the case number and the maximum possible priority index after all the marriages have been arranged.
Sample Input
Output for Sample Input
2
2
1 5
2 1
3
1 2 3
6 5 4
8 1 2
Case 1: 7
Case 2: 16
public class MarriageCeremonies { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.readInt(); int[][] priorityIndex = new int[n][n]; for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) priorityIndex[i][j] = in.readInt(); out.println("Case " + testNumber + ": " + solveViaDP(n, priorityIndex)); } public int solveViaDP(int n, int[][] priorityIndex) { int[][] dp = new int[2][1 << n]; for (int j = 0; j < n; ++j) dp[0 & 1][1 << j] = priorityIndex[0][j]; for (int i = 1; i < n; ++i) for (int mask = 0; mask < 1 << n; ++mask) for (int j = 0; j < n; ++j) if ((mask & (1 << j)) == 0) dp[i & 1][mask | (1 << j)] = Math.max(dp[i & 1][mask | (1 << j)], dp[(i - 1) & 1][mask] + priorityIndex[i][j]); return dp[(n - 1) & 1][(1 << n) - 1]; } }
Quick explanation of the solution
As n <= 16 according to the problem constraints, we can use a bit mask to represent a set of woman by an integer value.
dp[i][mask] = maximum priority index where i men have been married to set of women represented by mask
Base case: dp[0][1 << j] = priorityIndex[0][j] where 0 <= j < n
Recurrence relation: dp[i][mask | (1 << j)] = max over all mask s.t. jth bit (woman) is not set (is unmarried) in mask { dp[i - 1][mask] + priorityIndex[i][j] } Final result = dp[n - 1][(1 << n) - 1] which represent all men are married and the set of married women is complete.