![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Number of Ways to Wear Different Hats to Each Other in C++
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 −
return dp[idx, mask]
ret := add(ret, solve(idx + 1, mask))
for all i in v[idx]sk))
if (shift mask i bits to the right) is even, then
ret = add(ret, solve(idx + 1, mask OR 2^i))
dp[idx, mask] := ret
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
#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 ; int add(lli a, lli b){ return ((a % m) + (b % m)) % m; } int solve(int idx, int mask){ if (mask == req) return 1; if (idx == 42) return 0; if (dp[idx][mask] != -1) { return dp[idx][mask]; } int ret = add(ret, solve(idx + 1, mask)); for (int i : v[idx]) { if (!((mask >> i) & 1)) { ret = add(ret, solve(idx + 1, mask | (1 << i))); } } return dp[idx][mask] = ret; } 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