题解:P13016 [GESP202506 六级] 最大因数
b__b
·
2025-06-30 15:58:52
·
题解
定义 \mathrm{depth}_i 为树上第 i 个结点的深度(根节点的深度为 0 ),结点 x 和结点 y 的最近公共祖先为 \mathrm{LCA}(x,y) ,树上的结点 x 和结点 y 的距离 \mathrm{dist}_{x,y}=\mathrm{depth}_x+\mathrm{depth}_y-2\mathrm{depth}_{\mathrm{LCA}(x,y)} 。
于是问题就变成找到两个数所代表的结点的深度和最小公共祖先的深度。
我们先将题目转化一下。
对于编号为 k (2 \leq k \leq 10^9 )的结点,其父结点的编号为 k 的因数中除 k 以外最大的因数。
于是我们可以参照质因数分解的朴素算法算出一个结点到根结点的路径:
```cpp
//这个函数调用完后会将primes存储为k到根结点的路径,primenum表示路径的长度
template <int *primes, int &primenum> void getprimes(int k) {
primenum = 0;
for (int g = 2; g * g <= k; ++g)
while (!(k % g)) //这是一个质因数
primes[primenum++] = k, k /= g; //记录它的一个父节点后更新p
if (k != 1) primes[primenum++] = k; //还漏了一个质因数
if (primes[primenum - 1] != 1) primes[primenum++] = 1; //将根节点补上
}
```
计算完成后显然有 $\mathrm{depth}_p=\mathrm{primenum}-1$。
我们对于 $x$ 与 $y$ 分别调用一次上面的函数,这样 $x$ 与 $y$ 到根结点的路径和 $x$ 与 $y$ 的深度就算出来了。现在我们只需要算出 $\mathrm{LCA}(x,y)$。
定义 $\mathrm{path}_a$ 表示编号为 $a$ 的结点到根结点的路径。显然调用上面的函数后 $\mathrm{path}_x$ 与 $\mathrm{path}_y$ 就已经得到了。由于我们已经得到了 $\mathrm{path}_x$ 与 $\mathrm{path}_y$,因此我们只需要遍历 $\mathrm{path}_y$,遍历到一个结点时,如果它在 $\mathrm{path}_x$ 里,那么它显然就是 $\mathrm{LCA}(x,y)$。
具体实现时,由于 $\mathrm{path}_x$ 与 $\mathrm{path}_y$ 显然单调递减,于是我们可以直接二分查找优化复杂度。
找到 $\mathrm{LCA}(x,y)$ 后,设 $\mathrm{LCA}(x,y)$ 在 $\mathrm{path}_y$ 的第 $p$ 个位置,那么 $\mathrm{depth}_{\mathrm{LCA}(x,y)}=\mathrm{depth}_y-p$。
于是
$$
\begin{aligned}
\mathrm{dist}_{x,y}&=\mathrm{depth}_x+\mathrm{depth}_y-2\mathrm{depth}_{\mathrm{LCA}(x,y)}\\
&=\mathrm{depth}_x+\mathrm{depth}_y-2(\mathrm{depth}_y-p)\\
&=\mathrm{depth}_x-\mathrm{depth}_y+2p
\end{aligned}
$$
时间复杂度:
1. 在有 $n$ 个质因数的数里面 $2^n$ 显然是最小的数字,因此对于一个正整数 $a$,它的因数数量最多为 $\lfloor \log_2a \rfloor$。所以任何一个结点的深度最多是 $\lfloor \log_2a \rfloor$。因此上文的 getprimes 函数复杂度为 $\mathcal{O}(\log n)$。
2. 显然 $\mathrm{path}_x$ 的长度为 $\lfloor \log_2x \rfloor+1$,$\mathrm{path}_y$ 的长度为 $\lfloor \log_2y \rfloor+1$。在 $\mathrm{xp}$ 查找一个数的复杂度为 $\mathcal{O}(\log x)$,$\mathrm{yp}$ 里面的每一个数都要查找一次,总复杂度为 $\mathcal{O}((\log x)(\log y))$,在本题内可以接受。
代码:
```cpp
#include <cstdio>
#include <algorithm>
#include <functional>
int xprimes[32], yprimes[32], xprimenum, yprimenum;
template <int *primes, int &primenum> void getprimes(int p) {
primenum = 0;
for (int g = 2; g * g <= p; ++g) while (!(p % g)) primes[primenum++] = p, p /= g;
if (p != 1) primes[primenum++] = p;
if (primes[primenum - 1] != 1) primes[primenum++] = 1;
}
int main() {
int q;
scanf("%d", &q);
for (int x, y; q--;) {
scanf("%d%d", &x, &y), getprimes<xprimes, xprimenum>(x), getprimes<yprimes, yprimenum>(y);
for (int i = 0; i < yprimenum; ++i) if (*std::lower_bound(xprimes, xprimes + xprimenum, yprimes[i], std::greater<int>()) == yprimes[i]) {
printf("%d\n", xprimenum - yprimenum + 2 * i);
break;
}
}
}
```