The Wayback Machine - https://web.archive.org/web/20240804090145/https://www.geeksforgeeks.org/bitmasking-and-dynamic-programming-set-1-count-ways-to-assign-unique-cap-to-every-person/
Open In App

Count Ways To Assign Unique Cap To Every Person

Last Updated : 24 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Given n people and 100 types of caps labeled from 1 to 100, along with a 2D integer array caps where caps[i] represents the list of caps preferred by the i-th person, the task is to determine the number of ways the n people can wear different caps. Since the number of ways could be large, so return the result modulo 109 + 7.

Example:

Input: caps = { { 3, 4 }, { 4, 5 }, { 5 } }
Output: 1

Input: caps = { { 1, 2, 3 }, { 1, 2 }, { 3, 4 }, { 4, 5 } }
Output: 8

[Naive Approach] Using Backtracking – O(n*2100) time and O(n*2100) space

One very simple approach is that we iterating over each person and assigning them one of their preferred caps that hasn’t been assigned yet. However, this method becomes inefficient due to the high number of possible combinations, especially when each person has multiple preferences of caps.

Complexity Analysis of Naive Approach:

  • Each cap can be either taken or not take, so for a single person there are 2100 possible states to wear a cap.
  • And for each state, we could potentially iterate over all people, resulting in a time complexity of O(n*2100)
  • This complexity is huge and result in TLE.

[Expected Approach] Using DP + Bitmasking – O(100×2n) time and O(100×2n)

The inefficiency arises from tracking the state of each cap. Instead, we can shift our focus to the people and track which people have not yet been assigned a cap. This is more efficient because we only have at most 10 people, far fewer than the 100 caps. And with the help of Bitmasking we can keep track of which people have not yet been assigned a cap.

Bitmask Representation:

  • A bitmask is used to represent the state of whether each person has been assigned a cap.
  • If there are n people, the bitmask has n bits. A bit set to 1 means the corresponding person has been assigned a cap; 0 means they have not.
  • For instance, with 3 people, a bitmask 101 means the first and third persons have caps, while the second does not.

Dynamic Programming (DP) Approach:

  • We define a DP function dp(cap, mask), where cap is the current cap being considered, and mask is the bitmask representing the current assignment state.
  • Base Cases:
    • If mask indicates all people have caps (all bits set), return 1 because we’ve found a valid assignment.
    • If cap exceeds 100, return 0 because no further assignments can be made.
  • Recursive Case:
    • For each cap, decide whether to assign it to a person who prefers it and hasn’t been assigned a cap yet.
    • Calculate the number of ways by:
      1. Not taking (not considering) the current cap.
      2. Assigning the current cap to eligible people.

Code Implementation:

C++
#include <bits/stdc++.h>
using namespace std;

// Function to find the number of ways to assign caps to
// people such tcap each person gets a unique cap
int solve(int capId, int mask, int n, int mod,
          vector<vector<int> >& dp,
          vector<vector<int> >& capToPeople)
{

    // If all people have been assigned a cap, return 1
    if (mask == (1 << n) - 1)
        return 1;

    // If all caps have been considered and not all people
    // have caps, return 0
    if (capId == 101)
        return 0;

    // Check if the result for this state is already
    // computed
    if (dp[capId][mask] != -1)
        return dp[capId][mask];

    int res = 0;

    // Try assigning the current cap to each person who
    // likes it
    for (auto people : capToPeople[capId]) {

        // Check if the person already has a cap
        if ((1 << people) & mask)
            continue;

        // Assign the current cap to the person and move to
        // the next cap
        res = (res
               + solve(capId + 1, (1 << people) | mask, n,
                       mod, dp, capToPeople))
              % mod;
    }

    // Consider the case where the current cap is not
    // assigned to anyone
    res = (res
           + solve(capId + 1, mask, n, mod, dp,
                   capToPeople))
          % mod;

    // Store the result in dp array for future reference
    return dp[capId][mask] = res;
}

// Main function to calculate the number of ways to assign
// caps to people
int numberWays(vector<vector<int> >& caps)
{

    // Map caps to the list of people who prefer them
    vector<vector<int> > capToPeople(101);
    int n = caps.size();

    // Fill the capToPeople mapping
    for (int i = 0; i < n; i++) {
        for (auto cap : caps[i]) {
            capToPeople[cap].push_back(i);
        }
    }

    // Initialize dp array and other variables
    int capId = 0, mask = 0, mod = 1e9 + 7;
    vector<vector<int> > dp(101, vector<int>((1 << n), -1));

    // Call the solve function starting from the first cap
    return solve(capId, mask, n, mod, dp, capToPeople);
}

// Driver code
int main()
{
    vector<vector<int> > caps1
        = { { 3, 4 }, { 4, 5 }, { 5 } };
    cout << numberWays(caps1) << endl;

    vector<vector<int> > caps2
        = { { 1, 2, 3 }, { 1, 2 }, { 3, 4 }, { 4, 5 } };
    cout << numberWays(caps2) << endl;

    return 0;
}
Java
import java.util.*;

public class CapAssignment {
    static final int MOD = 1000000007;

    // Function to find the number of ways to assign caps to
    // people such that each person gets a unique cap
    public static int solve(int capId, int mask, int n,
                            int[][] dp,
                            List<Integer>[] capToPeople)
    {
        // If all people have been assigned a cap, return 1
        if (mask == (1 << n) - 1)
            return 1;

        // If all caps have been considered and not all
        // people have caps, return 0
        if (capId == 101)
            return 0;

        // Check if the result for this state is already
        // computed
        if (dp[capId][mask] != -1)
            return dp[capId][mask];

        int res = 0;

        // Try assigning the current cap to each person who
        // likes it
        for (int person : capToPeople[capId]) {
          
            // Check if the person already has a cap
            if ((mask & (1 << person)) != 0)
                continue;

            // Assign the current cap to the person and move
            // to the next cap
            res = (res
                   + solve(capId + 1, mask | (1 << person),
                           n, dp, capToPeople))
                  % MOD;
        }

        // Consider the case where the current cap is not
        // assigned to anyone
        res = (res
               + solve(capId + 1, mask, n, dp, capToPeople))
              % MOD;

        // Store the result in dp array for future reference
        return dp[capId][mask] = res;
    }

    // Main function to calculate the number of ways to
    // assign caps to people
    public static int numberWays(List<List<Integer> > caps)
    {
        // Map caps to the list of people who prefer them
        List<Integer>[] capToPeople = new ArrayList[101];
        for (int i = 0; i < 101; i++) {
            capToPeople[i] = new ArrayList<>();
        }

        int n = caps.size();

        // Fill the capToPeople mapping
        for (int i = 0; i < n; i++) {
            for (int cap : caps.get(i)) {
                capToPeople[cap].add(i);
            }
        }

        // Initialize dp array
        int[][] dp = new int[101][1 << n];
        for (int[] row : dp) {
            Arrays.fill(row, -1);
        }

        // Call the solve function starting from the first
        // cap
        return solve(0, 0, n, dp, capToPeople);
    }

    // Driver code
    public static void main(String[] args)
    {
        List<List<Integer> > caps1 = Arrays.asList(
            Arrays.asList(3, 4), Arrays.asList(4, 5),
            Arrays.asList(5));
        System.out.println(numberWays(caps1));

        List<List<Integer> > caps2 = Arrays.asList(
            Arrays.asList(1, 2, 3), Arrays.asList(1, 2),
            Arrays.asList(3, 4), Arrays.asList(4, 5));
        System.out.println(numberWays(caps2));
    }
}
Python
MOD = 1000000007

# Function to find the number of ways to assign caps to
# people such that each person gets a unique cap


def solve(capId, mask, n, dp, capToPeople):

    # If all people have been assigned a cap, return 1
    if mask == (1 << n) - 1:
        return 1

    # If all caps have been considered and not all people
    # have caps, return 0
    if capId == 101:
        return 0

    # Check if the result for this state is already computed
    if dp[capId][mask] != -1:
        return dp[capId][mask]

    res = 0

    # Try assigning the current cap to each person who likes it
    for person in capToPeople[capId]:

        # Check if the person already has a cap
        if mask & (1 << person):
            continue

        # Assign the current cap to the person and move to the next cap
        res = (res + solve(capId + 1, mask | (1 << person),
                           n, dp, capToPeople)) % MOD

    # Consider the case where the current cap is not assigned to anyone
    res = (res + solve(capId + 1, mask, n, dp, capToPeople)) % MOD

    # Store the result in dp array for future reference
    dp[capId][mask] = res
    return res

# Main function to calculate the number of ways to assign caps to people


def numberWays(caps):

    # Map caps to the list of people who prefer them
    capToPeople = [[] for _ in range(101)]
    n = len(caps)

    # Fill the capToPeople mapping
    for i in range(n):
        for cap in caps[i]:
            capToPeople[cap].append(i)

    # Initialize dp array
    dp = [[-1] * (1 << n) for _ in range(101)]

    # Call the solve function starting from the first cap
    return solve(0, 0, n, dp, capToPeople)


# Driver code
caps1 = [[3, 4], [4, 5], [5]]
print(numberWays(caps1))

caps2 = [[1, 2, 3], [1, 2], [3, 4], [4, 5]]
print(numberWays(caps2))
JavaScript
const MOD = 1000000007;

// Function to find the number of ways to assign caps to
// people such that each person gets a unique cap
function solve(capId, mask, n, dp, capToPeople)
{

    // If all people have been assigned a cap, return 1
    if (mask === (1 << n) - 1)
        return 1;

    // If all caps have been considered and not all people
    // have caps, return 0
    if (capId === 101)
        return 0;

    // Check if the result for this state is already
    // computed
    if (dp[capId][mask] !== -1)
        return dp[capId][mask];

    let res = 0;

    // Try assigning the current cap to each person who
    // likes it
    for (const person of capToPeople[capId]) {
        // Check if the person already has a cap
        if (mask & (1 << person))
            continue;

        // Assign the current cap to the person and move to
        // the next cap
        res = (res
               + solve(capId + 1, mask | (1 << person), n,
                       dp, capToPeople))
              % MOD;
    }

    // Consider the case where the current cap is not
    // assigned to anyone
    res = (res + solve(capId + 1, mask, n, dp, capToPeople))
          % MOD;

    // Store the result in dp array for future reference
    dp[capId][mask] = res;
    return res;
}

// Main function to calculate the number of ways to assign
// caps to people
function numberWays(caps)
{

    // Map caps to the list of people who prefer them
    const capToPeople = Array.from({length : 101}, () => []);
    const n = caps.length;

    // Fill the capToPeople mapping
    for (let i = 0; i < n; i++) {
        for (const cap of caps[i]) {
            capToPeople[cap].push(i);
        }
    }

    // Initialize dp array
    const dp = Array.from({length : 101},
                          () => Array(1 << n).fill(-1));

    // Call the solve function starting from the first cap
    return solve(0, 0, n, dp, capToPeople);
}

// Driver code
const caps1 = [ [ 3, 4 ], [ 4, 5 ], [ 5 ] ];
console.log(numberWays(caps1));

const caps2 = [ [ 1, 2, 3 ], [ 1, 2 ], [ 3, 4 ], [ 4, 5 ] ];
console.log(numberWays(caps2));

Output
1
8

Time Complexity: O(100×2n×n)

  • States: There are 100 possible capId values and 2n possible mask values.
  • Transitions: Each state transition involves checking at most n people.

Auxiliary Space: O(100×2n) for memoization.



Previous Article
Next Article

Similar Reads

Distribute M objects starting from Sth person such that every ith person gets arr[i] objects
Given an array arr[] consisting of N integers (1-based indexing) and two integers M and S, the task is to distribute M objects among N persons, starting from the position S, such that the ith person gets at most arr[i] objects each time. Examples: Input: arr[] = {2, 3, 2, 1, 4}, M = 11, S = 2Output: 1, 3, 2, 1, 4Explanation: The distribution of M (
8 min read
Number of hours after which the second person moves ahead of the first person if they travel at a given speed
Given three integers A, B and K. Initially, the first person was ahead of the second person by K kms. In every hour, the first person moves ahead by A kms and the second person moves ahead by B kms. The task is to print the number of hours after which the second person crosses the first. If it is impossible to do so then print -1. Examples: Input:
4 min read
Count of ways to distribute N items among 3 people with one person receiving maximum
Given an integer N, the task is to find the total number of ways to distribute N among 3 people such that: Exactly one person gets the maximum number of items among all the 3 people.Each person gets at least 1 item. Examples: Input: N = 5 Output: 3 Explanation: 3 ways to distribute the item among 3 people are {1, 1, 3}, {1, 3, 1} and {3, 1, 1}. Dis
7 min read
Count the number of ways a person can walk, roll or jump
A person has to cover a distance, He can either walk, roll, or jump, each of these actions covers one unit distance. These actions are represented by: walk: w, roll: r, jump: j. Each person is eligible for the trophy if they meet the following criteria : The Person rolled for less than 2 unit distance in total.The Person jumped less than 3 consecut
9 min read
Check if X can give change to every person in the Queue
Given an array of N integers where Ai denotes the currency of note that the i-th person has. The possible currencies are 5, 10, and 20. All the N people are standing in a queue waiting to buy an ice cream from X which costs Rs 5. Initially, X has an initial balance of 0. Check if X will be able to provide change for all people who are waiting to bu
7 min read
Maximum volume of cube for every person when edge of N cubes are given
Given an array of N integers which denotes the edges of N cubical structures respectively. Also given are M integers which denote the number of peoples. The task is to find the maximum amount of volume of a cube that can be given to every person. Note: Cubes can be cut off any shape from any of the N cubes. Examples: Input: a[] = {1, 1, 1, 2, 2}, m
10 min read
Sum of count of persons still performing the job whenever a person finishes job
Given two integers P denoting the number of people and a positive integer K. Each person is assigned with the same job which takes exactly K hours to finish. A condition is given that all of them can start performing their jobs exactly in X hours of interval. Count the number of persons still performing the job whenever a prior person finishes his/
6 min read
Count number of unique ways to paint a N x 3 grid
Given an integer N, the task is to paint a grid of size N x 3 using colors Red, Yellow, or Green while making such that no pair of adjacent cells has the same color. Print the number of distinct ways in which it is possible Examples: Input: N = 1Output: 12Explanation: Following 12 possible ways to paint the grid exists: Red, Yellow, RedYellow, Red,
7 min read
Count of ways to choose 4 unique position elements one from each Array to make sum at most K
Given four arrays A[], B[], C[], D[] and an integer K. The task is to find the number of combinations of four unique indices p, q, r, s such that A[p] + B[q] + C[r] + D[s] ≤ K. Examples: Input: A = {2, 3}, B = {5, 2}, C = {0}, D = {1, 2}, K = 6Output: 3Explanation: The following are the required combinations:{2, 2, 0, 1}, {2, 2, 0, 2}, {3, 2, 0, 1}
13 min read
Count ways to generate N digit number such that its every digit divisible by previous digit
Given a number N, the task is to count the number of ways to create an N digit number from digits 1 to 9 such that every digit is divisible by its previous digit that is if the number is represented by an array of digits A then A[i + 1] % A[i] == 0. print the answer modulo 109 + 7. Examples: Input: N = 2Output: 23Explanation: For N = 2 possible ans
15+ min read
Article Tags :
Practice Tags :
three90RightbarBannerImg