-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathBitMasking.cpp
More file actions
90 lines (73 loc) · 2.34 KB
/
Copy pathBitMasking.cpp
File metadata and controls
90 lines (73 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <bits/stdc++.h>
using namespace std;
//git tutorial
// 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;
}