[LeetCode] Closest Node to Path in Tree

2277. Closest Node to Path in Tree

You are given a positive integer n representing the number of nodes in a tree, numbered from 0 to n - 1 (inclusive). You are also given a 2D integer array edges of length n - 1, where edges[i] = [node1i, node2i] denotes that there is a bidirectional edge connecting node1i and node2i in the tree.

You are given a 0-indexed integer array query of length m where query[i] = [starti, endi, nodei] means that for the ith query, you are tasked with finding the node on the path from starti to endi that is closest to nodei.

Return an integer array answer of length m, where answer[i] is the answer to the ith query.

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
65
66
class Solution {
vector<vector<int>> adj;
int LCA[1000][22];
int level[1000];
void dfs(int u, int par, int lvl = 0) {
LCA[u][0] = par;
level[u] = lvl;
for(auto& v : adj[u]) {
if(v == par) continue;
dfs(v, u, lvl + 1);
}
}
void insert(int n) {
for(int j = 0; j < 21; j++) {
for(int i = 0; i < n; i++) {
if(LCA[i][j] == -1) continue;
LCA[i][j + 1] = LCA[LCA[i][j]][j];
}
}
}
int qry(int u, int v) {
if(level[u] < level[v]) swap(u, v);
int diff = level[u] - level[v];
for(int i = 0; diff; i++, diff/=2) {
if(diff&1) u = LCA[u][i];
}
if(u != v) {
for(int i = 21; i >= 0; i--) {
if(LCA[u][i] == LCA[v][i]) continue;
u = LCA[u][i];
v = LCA[v][i];
}
u = LCA[u][0];
}
return u;
}
public:
vector<int> closestNode(int n, vector<vector<int>>& edges, vector<vector<int>>& query) {
adj = vector<vector<int>>(n);
memset(LCA, -1, sizeof LCA);
for(auto& e : edges) {
adj[e[0]].push_back(e[1]);
adj[e[1]].push_back(e[0]);
}
dfs(0, -1);
insert(n);

vector<int> res;
for(auto& q: query) {
int s = q[0], e = q[1], u = q[2];
int plca = qry(s,e), plv = level[plca];
int slca = qry(s,u), slv = level[slca];
int elca = qry(e,u), elv = level[elca];
if(elv >= slv and elv >= plv) {
res.push_back(elca);
} else if(slv >= elv and slv >= plv) {
res.push_back(slca);
} else {
res.push_back(plca);
}
}

return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/21/PS/LeetCode/closest-node-to-path-in-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.