逆元&组合数&快速幂
首先是逆元的推导过程
这里提到的费马小定理:
然后我们知道组合数Ckn=Akn/Akk=n! / (n-k)! / k!
再根据我们之前推导出来的
设inv[x]为x % mod的逆元//mod为求余的值
再用快速幂求得阶乘,再用阶乘取得逆元
以下是快速幂:
然后用快速幂求得幂次方,再用幂次方求逆元:
inv[N - 1] = pow_mod(f[N - 1], mod - 2, mod); //逆推预处理阶乘的逆元,其中pow_mod为快速幂
for (int i = N - 2; i >= 0; i--) {
inv[i] = inv[i + 1] * (i + 1) % mod;//可理解为1/i!=1/(i+1)! *(i+1)
}
这里利用到的就是:
inv[a]=am-2=1/a(mod m)
可推得inv[x] % mod = 1/x;
可得 Ckn=Akn/Akk=n! / (n-k)! / k!=n! * inv[k] % mod * inv[n - k] % mod
即可通过快速幂和逆元求得组合数。
附上题目Bheith i ngra le
链接:https://ac.nowcoder.com/acm/contest/18362/B
来源:牛客网
Komorebi is a primary student who is learning how to draw a mountain.
First of all, he gets an m\times nm×n grid, and he can paint some cells black and others white. Let’s define a grid is good if:
All the black cells are connected.
For every column of the grid, if there are black cells, all the black cells must be connected and there must be one on the bottom.
Let’s call the height of the highest black cell in the ii-th column h_ih
i
. Specially, if there isn’t any black cell in the ii-th column, then