-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution2.cpp
41 lines (41 loc) · 1.11 KB
/
Solution2.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
class Solution {
public:
int closestMeetingNode(vector<int>& edges, int node1, int node2) {
int n = edges.size();
vector<vector<int>> g(n);
for (int i = 0; i < n; ++i) {
if (edges[i] != -1) {
g[i].push_back(edges[i]);
}
}
const int inf = 1 << 30;
using pii = pair<int, int>;
auto f = [&](int i) {
vector<int> dist(n, inf);
dist[i] = 0;
queue<int> q{{i}};
while (!q.empty()) {
i = q.front();
q.pop();
for (int j : g[i]) {
if (dist[j] == inf) {
dist[j] = dist[i] + 1;
q.push(j);
}
}
}
return dist;
};
vector<int> d1 = f(node1);
vector<int> d2 = f(node2);
int ans = -1, d = inf;
for (int i = 0; i < n; ++i) {
int t = max(d1[i], d2[i]);
if (t < d) {
d = t;
ans = i;
}
}
return ans;
}
};