From d6c796d8f542d01acd4a7e585d3a313f9bfb62a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Iv=C3=A1n=20Renison?= <85908989+IvanRenison@users.noreply.github.com> Date: Sat, 11 May 2024 20:13:22 -0300 Subject: [PATCH 1/2] Use `__lg` to make `treeJump` shorter It breaks the case when P is empty, but thats not an useful case --- content/graph/BinaryLifting.h | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/content/graph/BinaryLifting.h b/content/graph/BinaryLifting.h index b10b6c327..b14ceb12b 100644 --- a/content/graph/BinaryLifting.h +++ b/content/graph/BinaryLifting.h @@ -5,15 +5,14 @@ * Source: Folklore * Description: Calculate power of two jumps in a tree, * to support fast upward jumps and LCAs. - * Assumes the root node points to itself. + * Assumes that P is not empty and that the root node points to itself. * Time: construction $O(N \log N)$, queries $O(\log N)$ * Status: Tested at Petrozavodsk, also stress-tested via LCA.cpp */ #pragma once vector treeJump(vi& P){ - int on = 1, d = 1; - while(on < sz(P)) on *= 2, d++; + int d = 1 + __lg(sz(P) - 1); vector jmp(d, P); rep(i,1,d) rep(j,0,sz(P)) jmp[i][j] = jmp[i-1][jmp[i-1][j]]; From 5644ad7432d8739277cf57da32c4e259550b56c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Iv=C3=A1n=20Renison?= <85908989+IvanRenison@users.noreply.github.com> Date: Sun, 12 May 2024 20:18:50 -0300 Subject: [PATCH 2/2] Fix __lg(0) case and update description --- content/graph/BinaryLifting.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/content/graph/BinaryLifting.h b/content/graph/BinaryLifting.h index b14ceb12b..947d794e8 100644 --- a/content/graph/BinaryLifting.h +++ b/content/graph/BinaryLifting.h @@ -5,14 +5,14 @@ * Source: Folklore * Description: Calculate power of two jumps in a tree, * to support fast upward jumps and LCAs. - * Assumes that P is not empty and that the root node points to itself. + * Assumes the root node points to itself. * Time: construction $O(N \log N)$, queries $O(\log N)$ * Status: Tested at Petrozavodsk, also stress-tested via LCA.cpp */ #pragma once vector treeJump(vi& P){ - int d = 1 + __lg(sz(P) - 1); + int d = sz(P) < 2 ? 0 : 1 + __lg(sz(P) - 1); vector jmp(d, P); rep(i,1,d) rep(j,0,sz(P)) jmp[i][j] = jmp[i-1][jmp[i-1][j]];