Count Ways To Assign Unique Cap To Every Person
Last Updated :
24 Jul, 2024
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:
- Not taking (not considering) the current cap.
- 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));
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.
Please Login to comment...