Skip to content

Commit 456b510

Browse files
committed
Bitmasking
1 parent 499b15e commit 456b510

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/*
2+
There are 100 different types of caps each having a unique id from 1 to 100.
3+
Also, there are ‘n’ persons each having a collection of a variable number of caps.
4+
One day all of these persons decide to go in a party wearing a cap but to look unique
5+
they decided that none of them will wear the same type of cap.
6+
So, count the total number of arrangements or ways such that none of them is wearing the same type of cap.
7+
Since, number of ways could be large, so output modulo 1000000007 .
8+
*/
9+
#include<bits/stdc++.h>
10+
#define MOD 1000000007
11+
using namespace std;
12+
13+
vector<int>capList[101];
14+
int dp[1025][101];
15+
int allmask;
16+
17+
long long int CountWaysUtil(int mask, int i){
18+
if(mask == allmask)
19+
return 1;
20+
if(i>100)
21+
return 0;
22+
if(dp[mask][i] != -1)
23+
return dp[mask][i];
24+
25+
long long int ways = CountWaysUtil(mask,i+1);
26+
int size = capList[i].size();
27+
for(int j=0;j<size;j++){
28+
if(mask & (1<<capList[i][j]))
29+
continue;
30+
else
31+
ways+= CountWaysUtil(mask | (1<<capList[i][j]), i+1);
32+
ways%=MOD;
33+
}
34+
return dp[mask][i]=ways;
35+
}
36+
37+
void CountWays(int n){
38+
string temp,str;
39+
int x;
40+
for(int i=0;i<n;i++){
41+
getline(cin,str);
42+
stringstream ss(str);
43+
while(ss >> temp)
44+
{
45+
stringstream s;
46+
s << temp;
47+
s >> x;
48+
capList[x].push_back(i);
49+
}
50+
}
51+
allmask = (1<<n)-1;
52+
memset(dp,-1,sizeof dp);
53+
cout<<CountWaysUtil(0,1)<<endl;
54+
}
55+
56+
int main()
57+
{
58+
int n;
59+
cin>>n;
60+
cin.ignore();
61+
CountWays(n);
62+
return 0;
63+
}

geekforgeeks/BitMasking_&_DP/a.out

27.7 KB
Binary file not shown.

0 commit comments

Comments
 (0)