A permutation P is good if P[i] % i == 0 or i % P[i] == 0 for 1 ≤ i ≤ N. Given N ≤ 20, count the number of good permutations.
Show Answer
The final solution uses Bitmask DP to efficiently count the number of good permutations that satisfy the given condition.
#include <iostream>
#include <vector>
using namespace std;
int N; // Global variable for the size of the permutation
vector<int> dp; // DP array to store results of subproblems
// Recursive function to count the number of good permutations using Bitmask DP
int solve(int mask) {
if (mask == (1 << N) - 1) return 1; // Base case: all elements are placed
if (dp[mask] != -1) return dp[mask]; // Return already computed result
int pos = __builtin_popcount(mask) + 1; // Position to place the next element (1-based)
dp[mask] = 0; // Initialize current DP state
for (int i = 0; i < N; i++) {
// Check if the i-th element is not used and it satisfies the condition
if (!(mask & (1 << i)) && (pos % (i + 1) == 0 || (i + 1) % pos == 0)) {
dp[mask] += solve(mask | (1 << i)); // Recur with updated mask
}
}
return dp[mask];
}
int main() {
cout << "Enter the value of N (N <= 20): ";
cin >> N;
dp.assign(1 << N, -1); // Initialize DP array with -1 for all masks
int result = solve(0); // Start with an empty mask
cout << "Number of good permutations for N = " << N << " is: " << result << endl;
return 0;
}