Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 24e4c4b

Browse filesBrowse files
committed
fix LCA
1 parent 2f761be commit 24e4c4b
Copy full SHA for 24e4c4b

File tree

1 file changed

+11
-12
lines changed
Filter options

1 file changed

+11
-12
lines changed

‎lca.cpp

Copy file name to clipboardExpand all lines: lca.cpp
+11-12Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Lowest Common Ancestor by binary lifting
22
// https://youtu.be/8uowVvQ_-Mo?t=4306
3-
template<typename T> // T: type of cost
3+
template<typename T=int> // T: type of cost
44
struct lca {
55
int n, root, l;
66
vector<vector<int>> to;
@@ -38,30 +38,29 @@ struct lca {
3838
}
3939
}
4040
// LCA
41-
int operator()(int a, int b) {
42-
if (dep[a] > dep[b]) swap(a,b);
43-
int gap = dep[b]-dep[a];
41+
int up(int v, int k) {
4442
for (int i = l-1; i >= 0; --i) {
4543
int len = 1<<i;
46-
if (gap >= len) {
47-
gap -= len;
48-
b = par[b][i];
49-
}
44+
if (k >= len) k -= len, v = par[v][i];
5045
}
46+
return v;
47+
}
48+
int operator()(int a, int b) {
49+
if (dep[a] > dep[b]) swap(a,b);
50+
b = up(b, dep[b]-dep[a]);
5151
if (a == b) return a;
5252
for (int i = l-1; i >= 0; --i) {
53-
int na = par[a][i];
54-
int nb = par[b][i];
53+
int na = par[a][i], nb = par[b][i];
5554
if (na != nb) a = na, b = nb;
5655
}
5756
return par[a][0];
5857
}
5958
int length(int a, int b) {
60-
int c = lca(a,b);
59+
int c = (*this)(a,b);
6160
return dep[a]+dep[b]-dep[c]*2;
6261
}
6362
T dist(int a, int b) {
64-
int c = lca(a,b);
63+
int c = (*this)(a,b);
6564
return costs[a]+costs[b]-costs[c]*2;
6665
}
6766
};

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.