Lucas定理 + 隔板法 HDU3037

松鼠存豆问题与Lucas定理
本文探讨了一道有趣的数学问题——松鼠如何在不同的树中存豆子,使得总数不超过一定数量。该问题通过组合数学中的Lucas定理解决,涉及大数处理及取模运算。
部署运行你感兴趣的模型镜像

Saving Beans

 Although winter is far away, squirrels have to work day and night to save beans. They need plenty of food to get through those long cold days. After some time the squirrel family thinks that they have to solve a problem. They suppose that they will save beans in n different trees. However, since the food is not sufficient nowadays, they will get no more than m beans. They want to know that how many ways there are to save no more than m beans (they are the same) in n trees. 

Now they turn to you for help, you should give them the answer. The result may be extremely huge; you should output the result modulo p, because squirrels can’t recognize large numbers.

Input

The first line contains one integer T, means the number of cases. 

Then followed T lines, each line contains three integers n, m, p, means that squirrels will save no more than m same beans in n different trees, 1 <= n, m <= 1000000000, 1 < p < 100000 and p is guaranteed to be a prime.

Output

You should output the answer modulo p.

Sample Input

2
1 2 5
2 1 5

Sample Output

3
3

这个由隔板法得到答案是C_{n+m}^{m}

但是这里的 n ,m 的值太大了,直接算会T,所以用Lucas定理,取模再运算这个组合数。

Lucas内容:C_{n}^{m}=C_{m/p}^{n/p}*C_{m\%p}^{n\%p}\%p

#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
typedef long long ll;
const int maxn=1e5+5;
ll f[maxn];
ll quickpow(ll a,ll b,ll mod)
{
    ll ans=1;
    while(b)
    {
        if(b&1) ans=(ans*a)%mod;
        a=(a*a)%mod;
        b>>=1;
    }
    return ans;
}
ll n,m,p;
void init()
{
    f[0]=1;
    for(int i=1;i<=p;++i)
        f[i]=(f[i-1]*i)%p;
}
ll Lucas(ll n,ll m,ll p)
{
    ll res=1;
    while(n&&m)
    {
        ll a=n%p;
        ll b=m%p;
        if(a<b) return 0;
        res=(res*f[a]*quickpow((f[b]*f[a-b])%p,p-2,p))%p;
        n/=p;
        m/=p;
    }
    return res;
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        scanf("%lld%lld%lld",&n,&m,&p);
        init();
        long long ans=Lucas(n+m,m,p);
        printf("%lld\n",ans);
    }
}

 

您可能感兴趣的与本文相关的镜像

Dify

Dify

AI应用
Agent编排

Dify 是一款开源的大语言模型(LLM)应用开发平台,它结合了 后端即服务(Backend as a Service) 和LLMOps 的理念,让开发者能快速、高效地构建和部署生产级的生成式AI应用。 它提供了包含模型兼容支持、Prompt 编排界面、RAG 引擎、Agent 框架、工作流编排等核心技术栈,并且提供了易用的界面和API,让技术和非技术人员都能参与到AI应用的开发过程中

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值