Count and Score Conflict-Free Cap Distributions
Dynamic ProgrammingAuto-graded · 19 test casesLast updated
Count the ways to give each person a distinct acceptable item and find the best total value, using a bitmask DP over people or bounded backtracking.
A group of people each have a list of caps they would be happy to wear. Cap IDs run from 1 to H, and every cap has a fixed point value. You must give every person exactly one cap from their own list, and no cap may be given to more than one person.
Write a function that returns two numbers: how many different complete distributions exist, and the largest total point value that any complete distribution can reach.
Details
wishlists[i]holds the cap IDs acceptable to personi.values[c - 1]is the point value of capc, soH == len(values).- The score of a distribution is the sum of the values of the caps that were handed out. Each handed-out cap is counted once.
- People are distinguishable. If two people swap their caps, that is a different distribution, even when the total score is unchanged.
- Caps do not all need to be used. Only the people must be fully covered; partial distributions are not counted.
- Return
[count, best_score]. - If no complete distribution exists, return
[0, -1]. - If there are no people, there is exactly one (empty) distribution with score
0, so return[1, 0].
Constraints
1 <= H <= 120 <= len(wishlists) <= 8- Each wishlist contains distinct, valid cap IDs and may be empty.
0 <= values[c] <= 1,000,000- The count and the score both fit in a signed 32-bit integer, so no modulus is needed.
Think about how to combine the "number of ways" and the "best score" in one pass without counting any distribution twice. Under these small limits, compare a bounded backtracking search with a bitmask dynamic program.
Examples
Example 1
Input: cap_distributions([[1, 2], [2, 3]], [5, 2, 9])
Output: [3, 14]
Example 2
Input: cap_distributions([[1], [1]], [8])
Output: [0, -1]
Hints
Hint 1
Because there are at most 8 people, the set of people who already hold a cap fits in a bitmask with at most 256 states.
Hint 2
Process the caps one at a time. For each cap you either skip it or give it to exactly one eligible person who has no cap yet. The fixed cap order prevents counting the same distribution more than once.
Hint 3
When two partial distributions reach the same mask, add their counts but keep only the larger score. Use a marker such as None for unreachable states so that a real score of 0 is not confused with impossible.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Iterate over the caps in order, and keep a bitmask of which people already have a cap. With at most 8 people there are at most 256 masks.
For every mask we store two values:
counts[mask]: the number of ways to give caps to exactly the people inmask, using only the caps processed so far.best[mask]: the highest total value among those partial distributions, orNoneif the mask is unreachable.
For each cap, every reachable mask has these options:
- Skip the cap. The state stays the same. Starting the next layer as a copy of the current one does this.
- Give the cap to one eligible person without a cap. Move from
masktomask | bit. Addcounts[mask]to the new count, and update the new best score withbest[mask] + valueusing a maximum.
After all caps are processed, the full mask (1 << n) - 1 holds the answer.
Why counts add but scores take a maximum
Different histories can reach the same mask. Their counts are summed, because they are distinct distributions and each one can be completed in the same ways. Their scores are merged with a maximum, because what can still be gained from a state depends only on the remaining caps and people, not on how the state was reached. This is the standard optimal-substructure argument.
Why nothing is counted twice
Caps are handled in a fixed order, and each cap has exactly one decision: skip it, or give it to one specific person. A complete distribution fixes all these decisions, so it corresponds to exactly one path in the DP. A cap is used at most once because it lives in exactly one layer. A person gets at most one cap because only bits outside mask can be added. Unused caps are simply skipped, so we never require all caps to be used.
best[mask] is set exactly when counts[mask] > 0. If counts[full] == 0, no valid distribution exists and we return [0, -1]. Using None rather than 0 for "unreachable" keeps a genuine score of 0 separate from impossibility.
Edge cases
- No people: return
[1, 0]directly. - A person with an empty wishlist: their bit is never set, so the result is
[0, -1]. - Conflicts such as
[[1],[1]]: the full mask is unreachable, so[0, -1]. - Caps that nobody wants: the layer just copies the previous one.
- Swapping caps between two people: gives different paths, so both are counted.
Backtracking versus bitmask DP
Backtracking assigns people one by one, trying each free acceptable cap. It is simple, but its cost equals the number of valid assignments plus dead ends, which can reach about 20 million leaves when everyone accepts all 12 caps. The bitmask DP merges all histories that reach the same set of covered people, which brings the work down to a few tens of thousands of operations. Putting the mask over people (at most 8) is cheaper than over caps (up to 12).
Complexity
With n <= 8 people and H <= 12 caps:
- Time:
O(H * 2^n * n), plus the cost of building the eligibility masks. - Space:
O(2^n).
Reference solution
from typing import List
def cap_distributions(wishlists: List[List[int]], values: List[int]) -> List[int]:
n = len(wishlists)
if n == 0:
return [1, 0]
size = 1 << n
counts = [0] * size
best = [None] * size
counts[0] = 1
best[0] = 0
for cap, score in enumerate(values, 1):
eligible = 0
for person, choices in enumerate(wishlists):
if cap in choices:
eligible |= 1 << person
next_counts = counts.copy()
next_best = best.copy()
for mask in range(size):
if counts[mask] == 0:
continue
available = eligible & ~mask
while available:
bit = available & -available
available -= bit
new_mask = mask | bit
next_counts[new_mask] += counts[mask]
candidate = best[mask] + score
if next_best[new_mask] is None or candidate > next_best[new_mask]:
next_best[new_mask] = candidate
counts, best = next_counts, next_best
full = size - 1
if counts[full] == 0:
return [0, -1]
return [counts[full], best[full]]