- 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
- 49 lines of C++ from the credited upstream file count-non-adjacent-subsets-in-a-rooted-tree.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 6 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.
1234 56class Solution {7public:8 int countValidSubsets(vector<int>& parent, vector<int>& nums, int k) {9 static const int MOD = 1e9 + 7;10 11 const auto& merge = [&](const auto& a, const auto& b) {12 vector<int> result(size(a));13 for (int i = 0; i < k; ++i) {14 if (!a[i]) {15 continue;16 }17 for (int j = 0; j < k; ++j) {18 if (!b[j]) {19 continue;20 }21 result[(i + j) % k] = ((result[(i + j) % k] + static_cast<int64_t>(a[i]) * b[j]) % MOD);22 }23 }24 return result;25 };26 27 vector<vector<int>> adj(size(nums));28 for (int v = 1; v < size(parent); ++v) {29 adj[parent[v]].emplace_back(v);30 }31 vector<vector<vector<int>>> dp(size(nums), vector<vector<int>>(2, vector<int>(k)));32 for (int u = size(nums) - 1; u >= 0; --u) {33 vector<vector<int>> new_dp(2, vector<int>(k));34 new_dp[0][0] = 1;35 new_dp[1][nums[u] % k] = 1;36 for (const auto& v : adj[u]) {37 vector<int> dp2(k);38 for (int i = 0; i < k; ++i) {39 dp2[i] = (dp[v][0][i] + dp[v][1][i]) % MOD;40 }41 new_dp[0] = merge(new_dp[0], dp2);42 new_dp[1] = merge(new_dp[1], dp[v][0]);43 }44 dp[u] = move(new_dp);45 }46 return ((dp[0][0][0] + dp[0][1][0] - 1LL) + MOD) % MOD;47 }48};49