CSES - Shared codeLink to this code:
https://cses.fi/paste/411b99c7043f57b35332e0/
#include<bits/stdc++.h>
#define all(x) x.begin(), x.end()
#define ll long long
using namespace std;
template <typename T>
using bstring = basic_string<T>;
template <typename T>
using matrix = vector<vector<T>>;
const int MOD = 1e9 + 7;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
matrix <int> comp (1 << n, vector <int> (1<<n));
// checks for every pair of masks if they are compatible
for(int i = 0; i < (1<<n); i++){
for(int j = 0; j < (1<<n); j++){
int innactive = (~i)&(~j); // here a bit is on iff its inactive in both i and j
int last = -1; //last = least significant bit of the current segment of bits that are innactive in both i and j
// last = -1 is a code for not being on a segment of that sort
bool ok = 1;
for(int k = 0; k < n; k++){
if((1<<k)&innactive){
if(last == -1) // we enter a segment
last = k;
} else {
if(last != -1){ // we leave a segment
ok&=(k-last)%2 == 0;
last = -1;
}
}
}
if(last!=-1)
ok&=(n-last)%2 == 0;
comp[i][j] = ok;
}
}
matrix<ll> dp(m+2,vector<ll>(1<<n));
dp[1][0] = 1; // innitially theres nothing poking into column 1
for(int i = 2; i <= m+1; i++){
for(int mask = 0; mask < (1<<n); mask++){
int poss = (~mask)&((1<<n)-1); // sets up ~X' so that we can search X that are submasks of it
for(int sub = poss; sub; sub = (sub-1)&poss){
//note that comp[a][b] == comp[b][a]
dp[i][mask] += dp[i-1][sub]*comp[mask][sub];
}
dp[i][mask]+=dp[i-1][0]*comp[mask][0]; //our previous for loop doesnt go over mask 0, so we have to check it mannually
dp[i][mask]%=MOD;
}
}
cout << dp[m+1][0] << '\n';
return 0;
}