# Number of Ways to Wear Different Hats to Each Other in C++

C++Server Side ProgrammingProgramming

Suppose there are n people and 40 different types of hats those are labeled from 1 to 40. Now a 2D list is given called hats, where hats[i] is a list of all hats preferred by the i-th person. We have to find the number of ways that the n people wear different hats to each other. The answer may come very large, so return the answer modulo 10^9 + 7.

So, if the input is like [[4,6,2],[4,6]], then the output will be 4, as there are 4 different ways to choose, these are [4,6], [6,4], [2,4], [2,6].

To solve this, we will follow these steps −

• m = 10^9 + 7

• Define 2D array dp of size 55 x 2^11

• Define one 2D array v

• Define a function add(), this will take a, b,

• return ((a mod m) + (b mod m)) mod m

• Define a function solve(), this will take idx, mask,

• if mask is same as req, then −

• return 1

• if idx is same as 42, then −

• return 0

• if dp[idx, mask] is not equal to -1, then −

• for all i in v[idx]sk))

• if (shift mask i bits to the right) is even, then

• return ret

• From the main method do the following −

• initialize dp with -1

• n := size of x

• update v so that it can contain 50 elements

• for initialize i := 0, when i < size of x, update (increase i by 1), do −

• for all j in x[i]

• insert i at the end of v[j]

• req := (2^n) - 1

• ret := solve(0, 0)

• return ret

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
int m = 1e9 + 7;
int dp[55][1 << 11];
class Solution {
public:
vector<vector<int> > v;
int req ;
return ((a % m) + (b % m)) % m;
}
return 1;
if (idx == 42)
return 0;
}
for (int i : v[idx]) {
if (!((mask >> i) & 1)) {
}
}
}
int numberWays(vector<vector<int>>& x){
memset(dp, -1, sizeof dp);
int n = x.size();
v.resize(50);
for (int i = 0; i < x.size(); i++) {
for (int j : x[i]) {
v[j].push_back(i);
}
}
req = (1 << n) - 1;
int ret = solve(0, 0);
return ret;
}
};
main(){
Solution ob;
vector<vector<int>> v = {{4,6,2},{4,6}};
cout << (ob.numberWays(v));
}

## Input

{{4,6,2},{4,6}}

## Output

4
Published on 09-Jun-2020 07:23:07