classSolution { public: conststaticint maxn = 1e5 + 10; conststaticint maxm = 1e5 + 10; constint INF = 0x3f3f3f3f; int n, k; int ans = 0; vector<vector<int>> g; vector<int> values; vector<int> dp; voiddfs(int u, int fa) { dp[u] = values[u]; for (int i = 0; i < g[u].size(); ++i) { int v = g[u][i]; if (v == fa) continue; dfs(v, u); if (dp[v] % k != 0) { dp[u] += dp[v]; } } if (dp[u] % k == 0) ans++; } intmaxKDivisibleComponents(int _n, vector<vector<int>> &edges, vector<int> &_values, int _k) { n = _n; k = _k; g.resize(n); dp.resize(n); values = _values; for (auto &edge : edges) { int u = edge[0]; int v = edge[1]; g[u].emplace_back(v); g[v].emplace_back(u); } dfs(0, -1); return ans; } };
classSolution { public: conststaticint maxn = 1e5 + 10; conststaticint maxm = 1e5 + 10; constint INF = 0x3f3f3f3f; int n, k; int ans = 0; vector<vector<int>> g; vector<int> values; intdfs(int u, int fa) { int sum = values[u]; for (int i = 0; i < g[u].size(); ++i) { int v = g[u][i]; if (v == fa) continue; sum = (sum + dfs(v, u)) % k; } if(sum % k == 0) ans++; return sum; } intmaxKDivisibleComponents(int _n, vector<vector<int>> &edges, vector<int> &_values, int _k) { n = _n; k = _k; g.resize(n); values = _values; for (auto &edge : edges) { int u = edge[0]; int v = edge[1]; g[u].emplace_back(v); g[v].emplace_back(u); } dfs(0, -1); return ans; } };