Official

E - Distance on Large Perfect Binary Tree Editorial by en_translator


Let regard Vertex \(1\) as the root. For each vertex, let us call the distance from Vertex \(1\) as its depth. Also, for each non-leaf Vertex \(i\), let us call the subtree under Vertex \(2i\) as its left hand side and that of Vertex \((2i+1)\) as its right hand side.

We can precalculate \(2^n \mod 998244353\) for each integer \(n\) from \(0\) through \(2N\), inclusive, so that we can assume that these values can be obtained in an \(O(1)\) time.

For each vertex \(v\), we consider the number of “pairs of vertices \((i,j)\) of distance \(D\) such that the LCA (Lowest Common Ancestor) of \(i\) and \(j\) is \(v\),” which we will denote by \(f(v)\). What we want is the sum of \(f(v)\) over all the vertices.

Let \(d\) be the depth of \(v\).
If \(v=i\) or \(v=j\), then the other vertex can be arbitrarily chosen from any ancestor of \(v\) with depth \(d+D\). The number of such cases is either \(0\) or \(2^D\), only depending on whether or not \(d+D\) exceeds \(N-1\), so it can be found in an \(O(1\)) time.
Otherwise, for each \(0< k< D\), \(i\) can be arbitrarily chosen from any vertex of depth \(d+k\) in \(v\)’s left hand side, and \(j\) from any vertex of depth \(d+(D-k)\) in \(v\)’s right hand side, respectively. “The number of combinations of \(i\), chosen arbitrarily from any vertex of depth \(d+k\) in \(v\)’s left hand side, and \(j\), chosen arbitrarily from any vertex of depth \(d+(D-k)\) in \(v\)’s right hand side” is either \(0\) or \(2^{D-2}\), only depending on whether or not \(d+k\) and \(d+(D-k)\) exceeds \(N-1\), so with a proper case division, the sum of numbers of choices for all \(k\) can be obtained in a total of \(O(1)\) time.

Thus, we have seen that for each fixed \(v\) \(f(v)\) can be obtained in an \(O(1)\) time.

Since the tree is a perfect binary tree, we can see that \(f(v)\) only depends on \(v\)’s depth. Since there are \(2^d\) vertices of depth \(d\), we can obtain the sum of \(f(v)\) over all vertices of depth \(d=0,1,\ldots,N-1\) in an \(O(1)\) time respectively, hence the problem has been solved in a total of \(O(N)\) time.

posted:
last update: