From 237c620647db2e6684f144b90dd8d96a4c5ca60f Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Jun 2025 01:16:31 -0700 Subject: [PATCH 1/2] Create binary_lift.cpp --- Template/Binary_Lift/binary_lift.cpp | 74 ++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Template/Binary_Lift/binary_lift.cpp diff --git a/Template/Binary_Lift/binary_lift.cpp b/Template/Binary_Lift/binary_lift.cpp new file mode 100644 index 000000000..7f6186fff --- /dev/null +++ b/Template/Binary_Lift/binary_lift.cpp @@ -0,0 +1,74 @@ +using ll = long long; +const int MAXN = 100000; +const int LOGN = 17; +class Solution { +public: + vector> adj[MAXN]; + int up[MAXN][LOGN+1]; + int depth[MAXN]; + ll distRoot[MAXN]; + + void dfs(int cur, int parent) + { + up[cur][0] = parent; + for(auto &[v,w]: adj[cur]) + { + if(v == parent) continue; + depth[v] = depth[cur] + 1; + distRoot[v] = distRoot[cur] + w; + dfs(v, cur); + } + } + + int lca(int a, int b) + { + if(depth[a] < depth[b]) swap(a,b); + int diff = depth[a] - depth[b]; + for(int k = 0; k <= LOGN; k++){ + if(diff & (1<= 0; k--){ + if(up[a][k] != up[b][k]){ + a = up[a][k]; + b = up[b][k]; + } + } + return up[a][0]; + } + + ll dist(int a, int b) + { + int c = lca(a,b); + return distRoot[a] + distRoot[b] - 2*distRoot[c]; + } + + ll stepUp(int u, int k) { + for (int i=LOGN; i>=0; i--) { + if ((k>>i)&1) { + u = up[u][i]; + } + } + return u; + } + + void solve(vector>& edges) { + for (auto& edge: edges) + { + int u = edge[0], v = edge[1], w = edge[2]; + adj[u].push_back({v,w}); + adj[v].push_back({u,w}); + } + + depth[0] = 0; + distRoot[0] = 0; + dfs(0, 0); + + for(int k = 1; k <= LOGN; k++) { + for(int v = 0; v < n; v++) { + up[v][k] = up[up[v][k-1]][k-1]; + } + } + + // Solve your problem. + } From cbf27c08f43d6e3438343ce106a1e539c044250e Mon Sep 17 00:00:00 2001 From: wisdompeak Date: Sun, 15 Jun 2025 01:17:25 -0700 Subject: [PATCH 2/2] Update Readme.md --- Readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Readme.md b/Readme.md index 28e1d55b4..0e1dda6f8 100644 --- a/Readme.md +++ b/Readme.md @@ -1697,6 +1697,7 @@ [Graph](https://github.com/wisdompeak/LeetCode/tree/master/Template/Graph) [Bit_Manipulation](https://github.com/wisdompeak/LeetCode/tree/master/Template/Bit_manipulation) [RB_Tree](https://github.com/wisdompeak/LeetCode/tree/master/Template/RB_Tree) +[Binary_Lift](https://github.com/wisdompeak/LeetCode/tree/master/Template/Binary_Lift) [二维子矩阵求和](https://github.com/wisdompeak/LeetCode/tree/master/Template/Sub_Rect_Sum_2D) [二维差分数组](https://github.com/wisdompeak/LeetCode/tree/master/Template/Diff_Array_2D) [CPP_LANG](https://github.com/wisdompeak/LeetCode/tree/master/Template/CPP_LANG)