Skip to content

Commit 8ad6196

Browse files
authored
Create 2872. Maximum Number of K-Divisible Components
1 parent 3aa0b96 commit 8ad6196

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution {
2+
public:
3+
int ans = 0;
4+
5+
int dfs(int num, int& k, vector<int> &values, vector<vector<int>> &vt, int parent) {
6+
7+
int total = values[num];
8+
9+
for (const int &x : vt[num])
10+
total += x == parent ? 0 : dfs(x, k, values, vt, num);
11+
12+
total %= k;
13+
ans += !total;
14+
15+
return total;
16+
};
17+
18+
int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {
19+
vector<vector<int>> vt(n);
20+
for (const vector<int>& edge : edges) {
21+
int f = edge.front(), b = edge.back();
22+
vt[f].push_back(b);
23+
vt[b].push_back(f);
24+
}
25+
dfs(0, k, values, vt, 0);
26+
return ans;
27+
}
28+
};

0 commit comments

Comments
 (0)