File tree Expand file tree Collapse file tree 1 file changed +12
-7
lines changed Expand file tree Collapse file tree 1 file changed +12
-7
lines changed Original file line number Diff line number Diff line change 1
1
// Time: O(n)
2
2
// Space: O(n)
3
3
4
- // graph
4
+ // tree, bfs
5
5
class Solution {
6
6
public:
7
7
int collectTheCoins (vector<int >& coins, vector<vector<int >>& edges) {
@@ -23,13 +23,14 @@ class Solution {
23
23
u = v;
24
24
}
25
25
}
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);
32
30
}
31
+ }
32
+ for (int _ = 0 ; _ < DISTANCE; ++_) {
33
+ vector<int > new_q;
33
34
for (const auto & u : q) {
34
35
if (empty (adj[u])) {
35
36
assert (n == 1 );
@@ -39,7 +40,11 @@ class Solution {
39
40
adj[u].erase (v);
40
41
adj[v].erase (u);
41
42
--n;
43
+ if (size (adj[v]) == 1 ) {
44
+ new_q.emplace_back (v);
45
+ }
42
46
}
47
+ q = move (new_q);
43
48
}
44
49
return (n - 1 ) * 2 ;
45
50
}
You can’t perform that action at this time.
0 commit comments