题解:CF2187C Jerry and Tom

· · 题解

这里主要说一下怎么做到线性。

首先

f(x,y)=\begin{cases} \mathrm{dep}(y)-\mathrm{dep}(\mathrm{LCA}(x,y))&\mathrm{dep}(x)\geq\mathrm{dep}(y)\\ 0&\text{otherwise} \end{cases}

于是

\begin{aligned} \sum_{1\leq x,y\leq n,x\neq y} f(x,y)&=\sum_{1\leq x,y\leq n,x\neq y,\mathrm{dep}(x)\geq\mathrm{dep}(y)} (\mathrm{dep}(y)-\mathrm{dep}(\mathrm{LCA}(x,y)))\\ &=\sum_{1\leq x,y\leq n,x\neq y,\mathrm{dep}(x)\geq\mathrm{dep}(y)}\mathrm{dep}(y)-\sum_{1\leq x,y\leq n,x\neq y,\mathrm{dep}(x)\geq\mathrm{dep}(y)}\mathrm{dep}(\mathrm{LCA}(x,y)) \end{aligned}

因为 x=y 时,\mathrm{dep}(y)-\mathrm{dep}(\mathrm{LCA}(x,y))=0,所以方便起见我们可以不考虑 x\neq y,于是答案即为

\sum_{1\leq x,y\leq n,\mathrm{dep}(x)\geq\mathrm{dep}(y)}\mathrm{dep}(y)-\sum_{1\leq x,y\leq n,\mathrm{dep}(x)\geq\mathrm{dep}(y)}\mathrm{dep}(\mathrm{LCA}(x,y))

前一个和是容易线性计算的,考虑每个 \mathrm{dep}(y) 的贡献即可。于是我们只需考虑后一个和如何线性计算。

\begin{aligned} &\sum_{1\leq x,y\leq n,\mathrm{dep}(x)\geq\mathrm{dep}(y)}\mathrm{dep}(\mathrm{LCA}(x,y))\\ =&\frac{1}{2}(\sum_{1\leq x,y\leq n}\mathrm{dep}(\mathrm{LCA}(x,y))+\sum_{1\leq x,y\leq n,\mathrm{dep}(x)=\mathrm{dep}(y)}\mathrm{dep}(\mathrm{LCA}(x,y)))\\ =&\frac{1}{2}({\color{red}\sum_{1\leq x,y\leq n}\mathrm{dep}(\mathrm{LCA}(x,y))}+{\color{orange}\sum_{x}\mathrm{dep(x)}}+2{\color{green}\sum_{(x,y),\mathrm{dep}(x)=\mathrm{dep}(y)}\mathrm{dep}(\mathrm{LCA}(x,y))}) \end{aligned}

红色部分显然是所有子树大小的平方和,橙色部分也很简单,只需考虑如何线性计算绿色部分。把点按深度分组,问题转化为求每个深度的点集中所有点对的 LCA 深度之和。

考虑一个点集,设点集 S=\{u_1,u_2,...,u_{|S|}\}。将 u 按 dfs 序排序,利用经典性质:u_i 和 u_j 的 LCA 是 u_i,u_{i+1},...,u_j 这些点的所有相邻点对的 LCA 中深度最浅的,则:

\begin{aligned} \sum_{x,y\in S,x<y}\mathrm{dep}(\mathrm{LCA}(x,y))&= \sum_{1\leq i<j\leq |S|}\mathrm{dep}(\mathrm{LCA}(u_i,u_j))\\ &=\sum_{1\leq i<j\leq |S|}\min_{i\leq k<j}\mathrm{dep}(\mathrm{LCA}(u_k,u_{k+1})) \end{aligned}

预处理出相邻点对 LCA,则问题转化为一个类似于所有子区间的最小值之和的问题,这是经典的,单调栈即可。使用桶排序和 O(n)-O(1) LCA 即可做到 O(|S|)。

于是我们可以 O(n) 地计算绿色部分,这样这道题就以 O(n) 时间解决了。

看得懂的应该都会实现,就不放代码了。