Skip to content

Commit 9270fa5

Browse files
authored
Update collect-coins-in-a-tree.cpp
1 parent fa25b6a commit 9270fa5

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

C++/collect-coins-in-a-tree.cpp

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Time: O(n)
22
// Space: O(n)
33

4-
// graph
4+
// tree, bfs
55
class Solution {
66
public:
77
int collectTheCoins(vector<int>& coins, vector<vector<int>>& edges) {
@@ -23,13 +23,14 @@ class Solution {
2323
u = v;
2424
}
2525
}
26-
for (int _ = 0; _ < DISTANCE; ++_) {
27-
vector<int> q;
28-
for (int u = 0; u < size(coins); ++u) {
29-
if (size(adj[u]) == 1) {
30-
q.emplace_back(u);
31-
}
26+
vector<int> q;
27+
for (int u = 0; u < size(coins); ++u) {
28+
if (size(adj[u]) == 1) {
29+
q.emplace_back(u);
3230
}
31+
}
32+
for (int _ = 0; _ < DISTANCE; ++_) {
33+
vector<int> new_q;
3334
for (const auto& u : q) {
3435
if (empty(adj[u])) {
3536
assert(n == 1);
@@ -39,7 +40,11 @@ class Solution {
3940
adj[u].erase(v);
4041
adj[v].erase(u);
4142
--n;
43+
if (size(adj[v]) == 1) {
44+
new_q.emplace_back(v);
45+
}
4246
}
47+
q = move(new_q);
4348
}
4449
return (n - 1) * 2;
4550
}

0 commit comments

Comments
 (0)