BZOJ 4766: 文艺计算姬(矩阵树定理+行列式化简+快速幂)

描述

https://www.lydsy.com/JudgeOnline/problem.php?id=4766

求完全二分图 Kn,m 的生成树数量。(1 <= n,m,p <= 10^18)

思路

在博客停更之前,做最后一波连续疯狂的更新吧!

直接矩阵树定理搞一波,打个表发现答案是 nm1mn1 ,这种题打表是捷径,但是如果打表还取模的话就什么也发现不了。

我们考虑为什么。将拉普拉斯矩阵(爱怎么叫都行)的余子式M(1,1)画出来,如下:

m0110m1111n0110n

这里只画了个4阶的,具体是分成四块:前n-1行前n-1列只有主对角线为m,其余为0;后m行m列主对角线为n,其余为0;其他两块都是-1。

将前n-1行和后m-1行都加到第n行去,我们发现第n行的前n-1列没了,第n列到后面全是1。然后将第n行加到上方所有行去,-1全部阵亡,剩下一个下三角矩阵。答案显然就是 mn1nm1 了。

直接快速幂和慢速乘就行了。

代码

#include 

using namespace std;

long long n, m, p;

long long Mul(long long x, long long y){
    long long res = 0;
    while(y){
        if(y & 1)  res = (res + x) % p;
        x = (x << 1) % p;
        y >>= 1;
    }
    return res;
}

long long Pow(long long x, long long y){
    long long res = 1;
    while(y){
        if(y & 1)  res = Mul(res, x);
        x = Mul(x, x);
        y >>= 1;
    }
    return res;
}

int main(){

    scanf("%lld%lld%lld", &n, &m, &p);

    printf("%lld\n", Mul(Pow(n, m-1), Pow(m, n-1)));    
    return 0;
}

你可能感兴趣的:(数论,&,数学,BZOJ,快速幂,矩阵树定理)