HDU3037(隔板法,Lucas)

本文探讨了一个组合数学问题,即如何计算在特定条件下分配物品(如食物豆)到不同容器(如树)的方法数。通过使用隔板法简化问题,并应用卢卡斯定理解决大数情况下组合数的计算,最终给出了解决方案的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

http://acm.hdu.edu.cn/showproblem.php?pid=3037

  • Problem Description
    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

题意

有n棵存放食物的树,每棵树都可以存放非负数量的食物,使得储存的食物小于等于m,求所有方案数并mod p

思路

利用隔板法,设放入了k个球(0<=k<=m),本来有n个球,则一共有n+k个球,一共有n-1个板(两边不放板,隔出来即是n棵树),每个板最少要隔一个球,有n+k-1个空格,则有C(n+k-1,n-1)种放板法。
总数量sum即是k从0取到m,sum=C(n+0-1,n-1)+C(n+1-1,n-1)+…+C(n+m+1,n-1)
用C(i,j)=C(i-1,j-1)+C(i,j-1)化简为sum=C(n+m,n)

数据比较大,用卢卡斯计算C(n,m)%p

代码

#include <iostream>
typedef long long ll;
using namespace std;
int MOD;

ll f[100010];
void fac(int p)
{   //f[n] = n!
    f[0] = 1;
    for (int i=1; i<=p; ++i) f[i] = f[i-1] * i % p;
}

ll pow_mod(ll a, ll x, int p)
{
    ll sum = 1;
    while (x)
    {
        if (x & 1)
            sum = sum * a % p;
        a = a * a % p;
        x >>= 1;
    }
    return sum;
}

ll Lucas(ll n, ll k, int p)  //C (n, k) % p
{
    ll ret = 1;
    while (n && k)
    {
        ll nn = n % p, kk = k % p;
        if (nn < kk) return 0; 
        //inv (f[kk]) = f[kk] ^ (p-2) % p
        ret= ret* f[nn]* pow_mod (f[kk]* f[nn-kk]% p, p-2, p)% p;
        n /= p, k /= p;
    }
    return ret;
}

int main() {
    int t,n,m,p;
    cin>>t;
    while(t--) {
        cin>>n>>m>>p;
        fac(p);
        printf ("%lld\n", Lucas (n+m, m, p));
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值