JZPTREE Falling Factorial
Falling Factorial, Tree DP
Description
Given a tree, for every node $x$ compute $\begin{align}\sum_{i=1}^{n}{dist(x,i)^k}\end{align}$.
$n \le 50000, k \le 500$.
Solution
When we solve $k = 1$ or $k = 2$, we can simply use trick of 2-times DFS, and maintain both sum of distance and sum of square of distance.
However, when problem becomes harder, the time complexity of this method will get TLE, for its $O(nk^2)$ time to maintain sum of powers using binomial theorem.
There’re some general ways to deal these sum of power problems, one of which is using falling factorial.
- Definition : Falling factorial of $x$ at $k$, denoted as $x^{\underline{k}}$, equals to $x(x-1)\cdots (x-k+1)$, which is also known as $P_x ^ k$, where $P$ means permutation.
And we have: $x^k = \sum_{i=0}^{k}{S(k,i)\times x^{\underline{i}}}$, where $S(k, i)$ is the Stirling Number of the second kind.
As for $S$, we have a recurrence relation that $S(i,j) = S(i-1, j - 1)+ j \times S(i-1,j) $, we can pre-process all $S$ we need in $O(k^2)$ time.
Then let’s see how to maintain falling factorial in $O(k)$ time.
We have a identity of falling factorial that $(x+1)^{\underline{i}} = (x+1)x^{\underline{i-1}} = (x - i + 1 + i)x^{\underline{i-1}} = x^{\underline{i}} + i\times x^{\underline{i-1}}$.
Another way to prove it is using permutation’s properties.
Think about when we transfer answer from $son_x$ to $x$ or reversely, what we do is actually add $1$ to all numbers in a set.
Thus for case that $son_x \rightarrow x$, we have: $ans_x^{k} = ans_x^k + ans_{son}^{k} + k \times ans_{son}^{k-1}$, for all distance in the subtree of $x$ increased.
As for $fa_x \rightarrow x$, it’s all number in father’s answer increasing, but it is larger than what we need. So we should minus numbers $+2$ in subtree of $x$, for these numbers get $+1$ when calculating father’s answer and this time they get a $+1$ again. Then add original answer in subtree of $x$. That is:
$(all_{fa}+1)^{\underline{k}} - (all_x + 2)^{\underline{k}} + ans_x^k$. Split the expression out we get:
$ans_{fa}^k + k \times ans_{fa}^{k-1} - 2k ans_{x}^{k-1} - k(k-1)ans_x^{k-2}$ for all $k \ge 2$.
When $k = 1$ it’s $ans_x^1 = ans_{fa}^1 + ans_{fa}^0 - 2ans_{x}^{0}$ , and $ans_x^0 = ans_{fa}^0$ for $k = 0$.
1 |
|