题目来源:Light OJ 1102 Problem Makes Problem
题意:一个整数n分解成k个数相加有多少种方案 数字可以重复
思路:m个苹果放n个盒子有多少方案 允许盒子有空 盒子空对应0 答案是C(n+m-1, n-1)
首先如果不允许有空 答案是C(m-1, n-1) 插空法m个苹果有m-1个空档 在这m-1个空档里选n-1个分成了n部分 每部分都不是空的
现在允许为空 那么给每个盒子增加一个苹果 相当于n+m个苹果分成n份 n+m-1个空档里选n-1个 C(n+m-1, n-1)
每部分都至少为1 为1的其实是空的 是我开始加上去的 为的是方便用插空法
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long LL;
const LL mod = 1000000007;
const int maxn = 2000010;
//返回a^p mod n 快速幂
LL a[maxn];
LL pow_mod(LL a, LL p, LL n)
{
LL ans = 1;
while(p)
{
if(p&1)
{
ans *= a;
ans %= n;
}
a *= a;
a %= n;
p >>= 1;
}
return ans;
}
LL C(LL n, LL m)
{
LL x = a[n], y = a[n-m]*a[m]%mod;
return x*pow_mod(y, mod-2, mod)%mod;
}
int main()
{
a[0] = 1;
for(int i = 1; i <= 2000000; i++)
{
a[i] = a[i-1]*i;
a[i] %= mod;
}
int cas = 0;
int T;
scanf("%d", &T);
while(T--)
{
LL n, m;
scanf("%lld %lld", &n, &m);
printf("Case %d: %lld\n", ++cas, C(n+m-1, m-1));
}
return 0;
}