Bank app~35 min2s · 256 MBtarget O(2^n × n) time, O(2^n) spaceclassic twin: lc-1879dp
A bank's back office has n review cases and n analysts. Each case and each analyst carries a skill code: a number where every bit stands for one skill, and higher bits are rarer skills.
Pairing a case with an analyst costs the xor of their two codes. A skill that only one of them has adds its weight. Every analyst takes exactly one case. Find the lowest total cost.
Write assign_jobs(cases, analysts).
cases[i] is the skill code of case i, and analysts[j] is the skill code of analyst j. Both lists have the same length n.i to analyst j is cases[i] xor analysts[j].Input: cases = [1, 2, 3], analysts = [5, 3, 4]
Output: 10Let best[mask] be the cheapest cost of giving the first cases, as many as the mask has bits, to exactly the analysts in the mask. Bit j of the mask stands for analyst j.
| Step | What happens | best for masks 1, 2, 4, 3, 5, 6, 7 |
|---|---|---|
| [1] | Only the empty mask costs 0 | |
| [4] | One analyst takes case 0, whose code is 1 | 4, 2, 5 |
| [4] | Two analysts take cases 0 and 1 | 5, 10, 6 |
| [4] | All three take cases 0, 1 and 2 | 10 |
The best pairing gives case 0 to analyst 0 (cost 4), case 1 to analyst 2 (cost 6) and case 2 to analyst 1 (cost 0). The total is 10.
Input: cases = [6, 6], analysts = [6, 6]
Output: 0Equal codes cost nothing, so every pairing costs 0.
Input: cases = [9], analysts = [4]
Output: 13There is one pairing, and 9 xor 4 is 13.
1 ≤ n ≤ 150 ≤ cases[i], analysts[j] ≤ 10^6There are 15! = 1,307,674,368,000 ways to give 15 cases to 15 analysts, so trying every pairing is impossible.
The set of analysts already used has only 2^15 = 32,768 possibilities. Each looks at 15 analysts for the next case, so about half a million steps are enough.