-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
collect-coins-in-a-tree.cpp
51 lines (49 loc) · 1.38 KB
/
collect-coins-in-a-tree.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
50
51
// Time: O(n)
// Space: O(n)
// tree, bfs
class Solution {
public:
int collectTheCoins(vector<int>& coins, vector<vector<int>>& edges) {
static const int DISTANCE = 2;
vector<unordered_set<int>> adj(size(coins));
for (const auto& e : edges) {
adj[e[0]].emplace(e[1]);
adj[e[1]].emplace(e[0]);
}
int n = size(coins);
for (int i = 0; i < size(coins); ++i) {
int u = i;
while (size(adj[u]) == 1 && !coins[u]) {
const int v = *cbegin(adj[u]);
adj[u].erase(v);
adj[v].erase(u);
--n;
u = v;
}
}
vector<int> q;
for (int u = 0; u < size(coins); ++u) {
if (size(adj[u]) == 1) {
q.emplace_back(u);
}
}
for (int _ = 0; _ < DISTANCE; ++_) {
vector<int> new_q;
for (const auto& u : q) {
if (empty(adj[u])) {
assert(n == 1);
break;
}
const int v = *cbegin(adj[u]);
adj[u].erase(v);
adj[v].erase(u);
--n;
if (size(adj[v]) == 1) {
new_q.emplace_back(v);
}
}
q = move(new_q);
}
return (n - 1) * 2;
}
};