NEFU 628 组合数学

NEFU 628 Garden visiting

题目:

Description
There is a very big garden at Raven’s residence. We regard the garden as an n*m rectangle. Raven’s house is at the top left corner, and the exit of the garden is at the bottom right. He can choose to take one step to only one direction (up, down, left or right) each time. Raven wants to go out of the garden as quickly as possible, so he wonders how many routes he could choose.
Raven knows there are many possible routes, so he only wants to know the number, which is the result that the total number of possible routes modes a given value p. He knows it is a simple question, so he hopes you may help him to solve it.
Input
The first line of the input contains an integer T, which indicates the number of test cases.
Then it is followed by three positive integers n, m and p (1 <= n, m, p <= 10^5), showing the length and width of the garden and p to be the mod of the result.
Output
For each case, output one number to show the result (the sum modes p).
Sample Input
3
2 2 5
2 6 16
6 6 24
Sample Output
2
6
12

题意:

其实就是求C(n+m-2,m-1)%p;

思路:

这道题的p可能是素数,所以不能用lucas和逆元来算,所以选择分解因子的方法。就是对于C(n,m)=(n!)/(m!*(n-m)!);
其中的三个阶乘一定可以处理成多个素数平方的形式,计算出每个素数的指数都是什么,用快速幂乘一起就行了。

代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
#include <algorithm>
#define N 200000+5
using namespace std;
typedef long long LL;
int prime[N];
bool flag[N];
int cnt;
void init()//把范围内所有可能的素数都找出来
{
    for(int i=2;i<N;i++)
        if(flag[i]==false)
        {
            prime[++cnt]=i;
            for(int j=i*2;j<N;j+=i)
                flag[j]=true;
        }
}
LL work(LL a,LL b)//求一个数的阶乘含某一个素数的指数
{
    LL ans=0;
    while(a)
    {
        ans+=a/b;
        a/=b;
    }
    return ans;
}
LL quick_mod(LL a,LL b,LL m)//快速幂
{
    LL ans = 1;
    a %= m;
    while(b)
    {
        if(b & 1)
        {
            ans = ans * a % m;
            b--;
        }
        b >>= 1;
        a = a * a % m;
    }
    return ans;
}
LL solve(int n,int m,int p)
{
    LL ans=1;
    for(int i=1;i<=cnt&&prime[i]<=n;i++)
    {
        LL a,b,c;
        a=work(n,prime[i]);
        b=work(m,prime[i]);
        c=work(n-m,prime[i]);
        LL tmp=a-(b+c);
        ans*=quick_mod(prime[i],tmp,p);
        ans%=p;
    }
    return ans;
}
int main()
{
    int T;
    init();
    scanf("%d",&T);
    while(T--)
    {
        LL n,m,p;
        scanf("%lld%lld%lld",&n,&m,&p);
        n += m - 2;
        m--;
        LL ans=solve(n,m,p);
        printf("%lld\n",ans);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值