- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 64 lines of C++ from the credited upstream file 2338.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 9 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int idealArrays(int n, int maxValue) {4 5 6 const int maxLength = min(14, n);7 const vector<vector<int>> factors = getFactors(maxValue);8 9 10 11 12 vector<vector<long>> dp(maxLength + 1, vector<long>(maxValue + 1));13 vector<vector<long>> mem(n, vector<long>(maxLength, -1));14 long ans = 0;15 16 for (int j = 1; j <= maxValue; ++j)17 dp[1][j] = 1;18 19 for (int i = 2; i <= maxLength; ++i)20 for (int j = 1; j <= maxValue; ++j)21 for (const int k : factors[j]) {22 dp[i][j] += dp[i - 1][k];23 dp[i][j] %= kMod;24 }25 26 for (int i = 1; i <= maxLength; ++i)27 for (int j = 1; j <= maxValue; ++j) {28 dp[i][0] += dp[i][j];29 dp[i][0] %= kMod;30 }31 32 for (int i = 1; i <= maxLength; ++i) {33 34 35 ans += dp[i][0] * nCk(n - 1, i - 1, mem);36 ans %= kMod;37 }38 39 return ans;40 }41 42 private:43 static constexpr int kMod = 1'000'000'007;44 45 vector<vector<int>> getFactors(int maxValue) {46 vector<vector<int>> factors(maxValue + 1);47 for (int i = 1; i <= maxValue; ++i)48 49 for (int j = i * 2; j <= maxValue; j += i)50 factors[j].push_back(i);51 return factors;52 }53 54 long nCk(int n, int k, vector<vector<long>>& mem) {55 if (k == 0)56 return 1;57 if (n == k)58 return 1;59 if (mem[n][k] != -1)60 return mem[n][k];61 return mem[n][k] = (nCk(n - 1, k, mem) + nCk(n - 1, k - 1, mem)) % kMod;62 }63};64