KatInterview

Count and Score Conflict-Free Cap Distributions

Dynamic ProgrammingAuto-graded · 19 test cases
HardAuto-gradedDynamic Programmingbitmask-dpcountingbacktracking

Last 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 person i.
  • values[c - 1] is the point value of cap c, so H == 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 <= 12
  • 0 <= 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.