File tree Expand file tree Collapse file tree 1 file changed +11
-12
lines changed Expand file tree Collapse file tree 1 file changed +11
-12
lines changed Original file line number Diff line number Diff line change 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
44struct 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};
You can’t perform that action at this time.
0 commit comments