分解质因子和快速幂在求组合数的模中的应用

来源:互联网 发布:郭德纲相声知乎 编辑:程序博客网 时间:2024/06/05 05:49

感谢卷神与许神的指点
Description
求C(n,m)对k取模后的值,

Input
第一行有一个整数T,表示有T组数据(T≤10)

接下来有T行,每行有三个整数n,m,k,用空格隔开。

0≤n≤10^5,0≤m≤n,1≤k≤10^9+7

Output
对于每组数据,输出答案并换行

暴力的方式只适合n<=20的情况,dp[n][m] = dp[n-1][m-1]+dp[n-1][m]也只能在n<=4000的时候可行。于是我们只能先用分解质因数的方法把上下相同的质因数抵消一部分,再用快速幂的方式把剩下来的因数相乘并进行取模操作(毕竟剩下10^5个2等,还用最简单粗暴的方式相乘还是会TLE的)。

#include <cstdio>#include <cstring>#include <vector>#include <algorithm>#include <map>using namespace std;long long a[100100];long long n,m,k;vector<pair<int, int>> vec[100000];  //利用vector记录i的所有质因数。long long quick_power(long long n,long long m)     //这就是快速幂的一种写法{    long long ans = 1;    while (m) {        if (m&1) {                                                         //利用二进制看看最后一位是否为1            ans = ans*n%k;        }        n = n*n%k;        m>>=1;                                                 //右移一位    }    return ans;}void init()                                        //先把100000以内的所有的数进行分解质因数。就不用为每一组数据再重复计算了。{    for (int i = 2; i<=100000; i++) {       //因为n最大为100000,所以肯定能包含所有情况。        long long temp = i;        for (int j = 2; j*j<=temp; j++) {            if (temp%j == 0) {                long long c1 = 0;                while (temp%j == 0) {                    temp /= j;                    c1++;                }                vec[i].push_back(make_pair(j,c1));            }        }        if (temp > 1) {            vec[i].push_back(make_pair(temp, 1));        }    }}int main() {    long long t;    scanf("%lld",&t);    init();    for (int c = 1; c<=t; c++) {        memset(a, 0, sizeof(a));        scanf("%lld%lld%lld",&n,&m,&k);        for (long long i = n-m+1; i<=n; i++) {            for (int j = 0; j<vec[i].size(); j++) {                long long x = vec[i][j].first;                long long y = vec[i][j].second;                a[x] += y;                                           //记录分母上的所有因数x的出现次数。            }        }        for (int i = 2; i<=m; i++) {            for (int j = 0; j<vec[i].size(); j++) {                long long x = vec[i][j].first;                long long y = vec[i][j].second;                a[x] -= y;                 //进行抵消。            }        }        long long ans = 1;        for (int c = 2;c<=n; c++) {            if (a[c]!=0) {                ans = ans*quick_power(c, a[c])%k;                //进行遍历输出。            }        }        printf("%lld\n",ans);    }    return 0;}
0 0
原创粉丝点击