-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path1443.cpp
More file actions
43 lines (35 loc) · 1.05 KB
/
Copy path1443.cpp
File metadata and controls
43 lines (35 loc) · 1.05 KB
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
class Solution {
public:
int minTime(int n, vector<vector<int>> &edges, vector<bool> &hasApple) {
vector<vector<int>> adj(n, vector<int>());
for (auto &e : edges) {
adj[e[0]].push_back(e[1]);
adj[e[1]].push_back(e[0]);
}
stack<pair<int, int>> st;
int res = 0;
st.push({0, -1});
while (!st.empty()) {
if (st.top().first == -1) {
st.pop();
auto [crnt, par] = st.top();
st.pop();
int count = 0;
for (int c : adj[crnt]) {
if (c == par) continue;
count += hasApple[c];
}
res += count;
hasApple[crnt] = hasApple[crnt] || count;
continue;
}
auto [crnt, par] = st.top();
st.push({-1, -1});
for (int c : adj[crnt]) {
if (c == par) continue;
st.push({c, crnt});
}
}
return res * 2;
}
};