-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path2872.cpp
More file actions
29 lines (29 loc) · 981 Bytes
/
2872.cpp
File metadata and controls
29 lines (29 loc) · 981 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public:
long long dfs(int node, vector<vector<int>>& graph, vector<bool>& visited, vector<int>& values, int& res, int k) {
visited[node] = true;
long long currentSum = 0;
for (auto& neighbor : graph[node]) {
if (visited[neighbor]) continue;
long long sum = dfs(neighbor, graph, visited, values, res, k);
currentSum += sum;
}
currentSum += values[node];
if (currentSum % k == 0) {
res++;
return 0;
}
return currentSum;
}
int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {
int res = 0;
vector<vector<int>> graph(n);
vector<bool> visited(n, false);
for (auto& edge : edges) {
graph[edge[0]].push_back(edge[1]);
graph[edge[1]].push_back(edge[0]);
}
dfs(0, graph, visited, values, res, k);
return res;
}
};