-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathMinimum Time to Collect All Apples in a Tree.cpp
64 lines (56 loc) · 1.54 KB
/
Minimum Time to Collect All Apples 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
52
53
54
55
56
57
58
59
60
61
62
63
64
// Runtime: 389 ms (Top 31.30%) | Memory: 61.8 MB (Top 53.68%)
class DSU{
private:
vector<int> parent,rank ;
public:
DSU(int n){
rank.resize(n,1) ;
parent.resize(n) ;
iota(begin(parent),end(parent),0) ;
}
int find_parent(int node){
if(node == parent[node]) return node ;
return parent[node] = find_parent(parent[node]) ;
}
void Union(int u , int v){
int U = find_parent(u) , V = find_parent(v) ;
if(U == V) return ;
if(rank[U] < rank[V]) swap(U,V) ;
rank[U] += rank[V] ;
parent[V] = U ;
}
int getRank(int node){
return rank[parent[node]] ;
}
};
class Solution {
public:
vector<bool> dp ;
vector<bool> hasApple ;
vector<int> adj[100001] ;
vector<int> visited ;
void dfs(int src){
visited[src] = 1 ;
for(auto &nbr : adj[src]){
if(!visited[nbr]){
dfs(nbr) ;
dp[src] = dp[src] or dp[nbr] ;
}
}
}
int minTime(int n, vector<vector<int>>& edges, vector<bool>& hasApple) {
DSU dsu(n) ;
dp = hasApple ; visited.resize(n,0) ; this->hasApple = hasApple ;
for(auto &x : edges) adj[x[0]].push_back(x[1]) , adj[x[1]].push_back(x[0]) ;
dfs(0) ;
int start = -1 ;
for(int i = 0 ; i < n ; ++i ){
if(!dp[i]) continue ;
if(start == -1){
start = i ; continue ;
}
dsu.Union(start,i) ;
}
return (dsu.getRank(0) - 1) * 2 ;
}
};