题目传送门
分析:
我们要求
\(\frac{1}{n(n-1)}\sum_{i=1}^{n}\sum_{j=1}^{n}\varphi(a_{i}a_j)dist(i,j)\)
先看一下怎么求\(\varphi(a_{i}a_j)\)
回归欧拉函数本质的式子:
\(\varphi(xy)=xy\prod_{p|xy}(1-\frac{1}{p})\)
\(\varphi(x)\varphi(y)=xy\prod_{p|x}(1-\frac{1}{p})\prod_{p|y}(1-\frac{1}{p})\)
两式相除:
\(\frac{\varphi(x)\varphi(y)}{\varphi(xy)}=\frac{\prod_{p|x}(1-\frac{1}{p})\prod_{p|y}(1-\frac{1}{p})}{\prod_{p|xy}(1-\frac{1}{p})}\)
(感性)推理一下
\(~~~~\frac{\varphi(x)\varphi(y)}{\varphi(xy)}\)
\(=\prod_{p|gcd(x,y)}(1-\frac{1}{p})\)
\(=\frac{\varphi(gcd(x,y))}{gcd(x,y)}\)
所以
\(\varphi(xy)=\frac{\varphi(x)\varphi(y)gcd(x,y)}{\varphi(gcd(x,y))}\)
于是开始推式子:
\(~~~~\sum_{i=1}^{n}\sum_{j=1}^{n}\varphi(a_{i}a_j)dist(a_i,a_j)\)
\(=\sum_{i=1}^{n}\sum_{j=1}^{n}\frac{\varphi(a_i)\varphi(a_j)gcd(a_i,a_j)}{\varphi(gcd(a_i,a_j))}dist(i,j)\)
枚举\(gcd(a_i,a_j)=d\)
\(=\sum_{d=1}^{n}\frac{d}{varphi(d)}\sum_{i=1}^{n}\sum_{j=1}^{n}[gcd(a_i,a_j)=d]\varphi(a_i)\varphi(a_j)dist(i,j)\)
令\(f(d)=\sum_{i=1}^{n}\sum_{j=1}^{n}[gcd(a_i,a_j)=d]\varphi(a_i)\varphi(a_j)dist(i,j)\)
不好求
我们再令\(F(d)=\sum_{i=1}^{n}\sum_{j=1}^{n}[d|gcd(a_i,a_j)]\varphi(a_i)\varphi(a_j)dist(i,j)\)
可以看出\(F(i)=\sum_{d|i}f(d)\)
于是乎\(f(i)=\sum_{d|i}\mu(\frac{i}{d})F(d)\)
我们知道\(F(d)\)后,便可以\(O(nlogn)\)的时间求出\(f(d)\)
考虑每一个\(d\),由于\(d|gcd(a_i,a_j)\),所以满足\(d|a_i\)的点都会加入,即\(\lfloor\frac{n}{d}\rfloor\)个点
总点数是\(O(nlogn)\)级别
对于每个\(d\),构建虚树,设其中有\(m\)个点,设\(v_i=\varphi(a_i)\)
\(F(d)=\sum_{i=1}^{m}\sum_{j=1}^{m}v_i v_j dist(i,j)\)
\(=\sum_{i=1}^{m}\sum_{j=1}^{m}v_i v_j (dpt(i)+dpt(j)-2dpt(LCA(i,j)))\)
展开
\(=\sum_{i=1}^{m}\sum_{j=1}^{m}v_i v_j dpt(i)+\sum_{i=1}^{m}\sum_{j=1}^{m}v_i v_j dpt(j)-2\sum_{i=1}^{m}\sum_{j=1}^{m}v_i v_j dpt(LCA(i,j))\)
前面俩其实等价
\(=2\sum_{i=1}^{m}\sum_{j=1}^{m}v_i v_j dpt(i)-2\sum_{i=1}^{m}\sum_{j=1}^{m}v_i v_j dpt(LCA(i,j))\)
前面的直接预处理可以算,后面的树形\(dp\)计算每个点为\(LCA\)时整棵子树的总和
于是这道题就解决了,复杂度\(O(nlog^{2}n)\)
一道很好(丧病)的数论大礼包+虚树+树形dp的题
写好了调半天
#include
#include
#include
#include
#include
#include
#include