-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path0834.cpp
More file actions
50 lines (42 loc) · 1.44 KB
/
Copy path0834.cpp
File metadata and controls
50 lines (42 loc) · 1.44 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
44
45
46
47
48
49
50
class Solution {
public:
vector<int> sumOfDistancesInTree(int n, vector<vector<int>> &edges) {
vector<vector<int>> adj(n);
vector<int> res(n), count(n, 1);
for (const auto &edge : edges) {
adj[edge[0]].push_back(edge[1]);
adj[edge[1]].push_back(edge[0]);
}
using record_t = tuple<int, int>;
stack<record_t> st;
for (st.emplace(-1, 0); !st.empty();) {
if (get<1>(st.top()) != -1) {
const auto [parent, root] = st.top();
st.emplace(-1, -1);
for (const auto next : adj[root]) {
if (next == parent) continue;
st.emplace(root, next);
}
continue;
}
st.pop();
const auto [parent, root] = st.top();
st.pop();
for (const auto next : adj[root]) {
if (next == parent) continue;
count[root] += count[next];
res[root] += res[next] + count[next];
}
}
for (st.emplace(-1, 0); !st.empty();) {
const auto [parent, root] = st.top();
st.pop();
for (const auto next : adj[root]) {
if (next == parent) continue;
res[next] = res[root] - count[next] + (n - count[next]);
st.emplace(root, next);
}
}
return res;
}
};