题解 CF451E 【Devu and Flowers】
An_Account · · 题解
首先,一句话题意:
有
如果盒子没有容纳限制,那么这个题就是一道经典的组合数学题,答案直接
下面介绍两种方法。
1.母函数
这题的母函数很容易表示出来,为
答案则为
我着重介绍以下的方法
2.状压+组合数+容斥原理+Lucas定理
注意到除了
因此,我们枚举状态
方案总数比较简单,为
我们将所有多放的球从总数中剔除出去,则剩下
for (int i=0;i<(1<<n);i++) {
LL cnt=s;
for (int j=1;j<=n;j++)
if (i&(1<<(j-1)))
cnt-=f[j]+1;
if (cnt<0) continue;
res=(res+C(cnt+n-1,n-1))%mod;
}
但注意,这并不是最终的答案,因为假如我们计算出了一个放满了
所以我们使用容斥原理,若状态中有奇数个盒子超出了范围,那么就在
for (int i=0;i<(1<<n);i++) {
LL cnt=s;int del=1;
for (int j=1;j<=n;j++)
if (i&(1<<(j-1)))
cnt-=f[j]+1,del=-del;
if (cnt<0) continue;
res=(res+C(cnt+n-1,n-1)*(LL)del)%mod;
}
最后说一下Lucas定理:解决大组合数取模。注意此题中组合数的第一项是一个可能为
LL Lucas(LL a,LL b) {
if (a<=mod&&b<=mod) return C(a,b);
return C(a%mod,b%mod)*Lucas(a/mod,b/mod)%mod;//Lucas
}
附上AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define LL long long
const LL mod=1e9+7;
LL Pow(LL x,LL y) {
LL res=1;
while (y) {
if (y&1) res=res*x%mod;
x=x*x%mod,y>>=1;
}
return res;
}
LL C(int n,int r) {
if (n<r) return 0;
r=min(r,n-r);
LL res=1,a=1,b=1;
for (int i=1;i<=r;i++)
a=a*(n-i+1)%mod,b=b*i%mod;
res=res*a%mod*Pow(b,mod-2)%mod;
return res;
}
LL Lucas(LL a,LL b) {
if (a<=mod&&b<=mod) return C(a,b);
return C(a%mod,b%mod)*Lucas(a/mod,b/mod)%mod;
}
LL f[21];
LL solve(int n,LL s) {
LL res=0;
for (int i=0;i<(1<<n);i++) {
LL cnt=s;int del=1;
for (int j=1;j<=n;j++)
if (i&(1<<(j-1)))
cnt-=f[j]+1,del=-del;
if (cnt<0) continue;
res=(res+Lucas(cnt+n-1,n-1)*(LL)del)%mod;
}
return (res+mod)%mod;
}
int main() {
int n;LL s;
while (~scanf("%d%lld",&n,&s)) {
for (int i=1;i<=n;i++) scanf("%lld",&f[i]);
printf("%lld\n",solve(n,s));
}
}