- 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
- 88 lines of C++ from the credited upstream file count-ways-to-choose-coprime-integers-from-rows.cpp.
- The implementation visibly relies on sequence storage, hash lookup, cached states.
- 12 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.
123 45class Solution {6public:7 int countCoprime(vector<vector<int>>& mat) {8 static const int MOD = 1e9 + 7;9 10 const auto& linear_sieve_of_eratosthenes = [](int n) { 11 vector<int> spf(n + 1, -1);12 vector<int> primes;13 for (int i = 2; i <= n; ++i) {14 if (spf[i] == -1) {15 spf[i] = i;16 primes.emplace_back(i);17 }18 for (const auto& p : primes) {19 if (i * p > n || p > spf[i]) {20 break;21 }22 spf[i * p] = p;23 }24 }25 return spf;26 };27 28 29 const auto& mobius = [](const auto& spf) { 30 vector<int> mu(size(spf));31 for (int i = 1; i < size(mu); ++i) {32 mu[i] = i == 1 ? 1 : (spf[i / spf[i]] == spf[i] ? 0 : -mu[i / spf[i]]);33 }34 return mu;35 };36 37 int mx = 0;38 for (const auto& row : mat) {39 mx = max(mx, ranges::max(row));40 }41 const auto& mu = mobius(linear_sieve_of_eratosthenes(mx));42 vector<int64_t> dp(mx + 1, 1);43 for (const auto& row : mat) {44 unordered_map<int, int> cnt;45 for (const auto& x : row) {46 ++cnt[x];47 }48 for (int i = 1; i <= mx; ++i) {49 int total = 0;50 for (int j = i; j <= mx; j += i) {51 total = (total + cnt[j]) % MOD;52 }53 dp[i] = (dp[i] * total) % MOD;54 } 55 }56 int result = 0;57 for (int i = 1; i <= mx; ++i) {58 result = (result + (((dp[i] * mu[i]) % MOD + MOD) % MOD)) % MOD;59 }60 return result;61 }62};63 64 65666768class Solution2 {69public:70 int countCoprime(vector<vector<int>>& mat) {71 static const int MOD = 1e9 + 7;72 73 unordered_map<int, int> dp;74 dp[0] = 1;75 for (const auto& row : mat) {76 unordered_map<int, int> new_dp;77 for (const auto& x : row) {78 for (const auto& [g, c] : dp) {79 const auto& ng = gcd(g, x);80 new_dp[ng] = (new_dp[ng] + c) % MOD;81 }82 }83 dp = move(new_dp);84 }85 return dp[1];86 }87};88