forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
maximum-number-of-k-divisible-components.cpp
49 lines (47 loc) · 1.43 KB
/
maximum-number-of-k-divisible-components.cpp
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Time: O(n)
// Space: O(n)
// bfs, greedy
class Solution {
public:
int maxKDivisibleComponents(int n, vector<vector<int>>& edges, vector<int>& values, int k) {
vector<vector<int>> adj(n);
for (const auto& e : edges) {
adj[e[0]].emplace_back(e[1]);
adj[e[1]].emplace_back(e[0]);
}
const auto& bfs = [&]() {
vector<int> cnt(n);
for (int u = 0; u < n; ++u) {
cnt[u] = size(adj[u]);
}
int result = 0;
vector<int> dp(size(values));
transform(cbegin(values), cend(values), begin(dp), [&](const auto& x) {
return x % k;
});
vector<int> q;
for (int u = 0; u < n; ++u) {
if (cnt[u] == 1) {
q.emplace_back(u);
}
}
while (!empty(q)) {
vector<int> new_q;
for (const auto& u : q) {
if (!dp[u]) {
++result;
}
for (const auto& v : adj[u]) {
dp[v] = (dp[v] + dp[u]) % k;
if (--cnt[v] == 1) {
new_q.emplace_back(v);
}
}
}
q = move(new_q);
}
return max(result, 1);
};
return bfs();
}
};