CodeForces - 451E Devu and Flowers【多重集下的组合数+容斥】

Devu wants to decorate his garden with flowers. He has purchased n boxes, where the i-th box contains fi flowers. All flowers in a single box are of the same color (hence they are indistinguishable). Also, no two boxes have flowers of the same color.

Now Devu wants to select exactly s flowers from the boxes to decorate his garden. Devu would like to know, in how many different ways can he select the flowers from each box? Since this number may be very large, he asks you to find the number modulo (109 + 7).

Devu considers two ways different if there is at least one box from which different number of flowers are selected in these two ways.

Input

The first line of input contains two space-separated integers n and s (1 ≤ n ≤ 20, 0 ≤ s ≤ 1014).

The second line contains n space-separated integers f1, f2, … fn (0 ≤ fi ≤ 1012).

Output

Output a single integer — the number of ways in which Devu can select the flowers modulo (109 + 7).


题目分析

多重集下的组合数

在这篇博客里我们对下面的式子给出了证明

a n s = C k + m 1 k 1 i = 1 k C k + m n i 2 k 1 + 1 <= i , j <= k , i ! = j C k + m n i n j 3 k 1 . . . + ( 1 ) k C k + m i = 1 k n i ( k + 1 ) k 1

考虑一下要怎么样应用这个式子
观察到n的范围很小,所以从n入手

我们枚举 x = 0 ~ 2 n 1
对于每一个x,设其二进制表示下共有p位为1
分别为 i 1 , i 2 , . . . , i p
于是可以用这个x表示上式中的一项 ( 1 ) p C n + m f i 1 f i 2 . . . f i p ( p + 1 ) n 1

那么每个 x = 0 ~ 2 n 1 就可以用来唯一的描述上式中的一项
这点从二进制角度证明很显然

在考虑每一项的组合数 C x y
由于x可能很大,所以稍作变换

C n + m 1 n 1 为例
C n + m 1 n 1 = A n + m 1 n 1 / ( n 1 ) ! = ( n + m 1 ) ! [ ( n + m 1 ) ( n 1 ) ] ! i = 1 n 1 i n v [ i ] = i = m + 1 n + m 1 i i = 1 n 1 i n v [ i ]
这样就限制其复杂度可以以O(n)记


#include<iostream>
#include<vector>
#include<algorithm>
#include<queue>
#include<cstring>
#include<cstdio>
using namespace std;
typedef long long lt;

lt read()
{
    lt f=1,x=0;
    char ss=getchar();
    while(ss<'0'||ss>'9'){if(ss=='-')f=-1;ss=getchar();}
    while(ss>='0'&&ss<='9'){x=x*10+ss-'0';ss=getchar();}
    return f*x;
}

const lt mod=1e9+7;
const int maxn=50;
lt a[maxn],inv[maxn];
lt ans;

lt C(lt n,lt m)
{
    if(n<0||m<0||n<m)return 0;
    if(n%mod==0||m==0)return 1;
    lt res=1;
    for(lt i=n-m+1;i<=n;++i)
    res*=(i%mod),res%=mod;
    for(int i=1;i<=m;++i)
    res*=inv[i],res%=mod;
    return res;
}

lt qpow(lt b,lt k)
{
    lt res=1;
    while(k>0)
    {
        if(k&1)res=(res*b)%mod;
        b=(b*b)%mod;
        k>>=1;
    }
    return res;
}

int main()
{
    lt n=read(),m=read();
    for(int i=1;i<=n;++i)a[i]=read();
    for(int i=1;i<=20;++i)inv[i]=qpow(i,mod-2);

    ans=C(n+m-1,n-1)%mod;
    for(int i=1;i<=(1<<n)-1;++i)
    {
        lt k=n+m,p=0;
        for(int j=0;j<n;++j)
        if((1<<j)&i)p++,k-=a[j+1];
        k-=p+1;
        if(p&1) ans-=C(k,n-1),ans%=mod;
        else ans+=C(k,n-1),ans%=mod;
    }
    printf("%lld",(ans+mod)%mod);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/niiick/article/details/81745819