Skip to content

[pull] master from wisdompeak:master #324

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 15, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
74 changes: 74 additions & 0 deletions Template/Binary_Lift/binary_lift.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
using ll = long long;
const int MAXN = 100000;
const int LOGN = 17;
class Solution {
public:
vector<pair<int,int>> 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<<k)) a = up[a][k];
}
if(a == b) return a;
for(int k = LOGN; k >= 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<vector<int>>& 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.
}