CodeForces 451E Devu and Flowers (容斥+组合)

本文解析 CodeForces 上一道关于组合数学的问题,探讨了在限定条件下,计算铺满特定长度区域的不同花卉组合方案数量的方法。通过容斥原理和隔板法,提供了一种有效求解的算法。

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

题目链接:http://codeforces.com/problemset/problem/451/E

#include<bits/stdc++.h>
using namespace std;

#define debug puts("YES");
#define rep(x,y,z) for(int (x)=(y);(x)<(z);(x)++)
#define ll long long

#define lrt int l,int r,int rt
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define root l,r,rt
#define mst(a,b) memset((a),(b),sizeof(a))
#define pii pair<int,int>
#define fi first
#define se second
#define mk(x,y) make_pair(x,y)
const int mod=1e9+7;
const int maxn=1e5+4;
const int maxm=1e5+100;
const int ub=1e6;
ll powmod(ll x,ll y){ll t; for(t=1;y;y>>=1,x=x*x%mod) if(y&1) t=t*x%mod; return t;}
ll gcd(ll x,ll y){return y?gcd(y,x%y):x;}
/*
题目大意:给定n种花,每种花有限定数量,
问铺满长度n有多少种不同的方案数。

题目分析:观察到n范围很小其他数字的范围大的吓人。。。T_T
然后考虑容斥,假如没有数量限制,其用隔板法(或者广义二项式)
可以轻松得到答案:C(n+s-1,s),
那么我们假如目标要去除其x1>=a1+1的方案数,
不妨直接在s上面变动,s变为s-a1-1,这样问题又是隔板法解决,
对于消去重复影响的过程,我们用容斥解决,这道题可以暴力也可以搜索,
搜索复杂度低些,暴力也能过。。。然后因为n十分小,组合数所用的复杂度也很小。
详见代码。

*/
int bitcnt(int x){int ret=0;while(x) x-=x&-x,ret++;return ret;}
ll n,s,a[30];
ll fac[30],inv[30];
void init(){
    fac[0]=1LL;for(int i=1;i<30;i++) fac[i]=fac[i-1]*i%mod;
    inv[29]=powmod(fac[29],mod-2);
    for(int i=28;i>=0;i--) inv[i]=inv[i+1]*(i+1)%mod;
}
ll C(ll p,ll q){
    ll tp=1LL;
    rep(i,0,q) tp=tp*((p-i)%mod)%mod;///细节
    tp=tp*inv[q]%mod;
    return tp;
}
int main(){
    init();///cout<<C(3,2)<<endl;
    scanf("%lld%lld",&n,&s);
    rep(i,0,n) scanf("%lld",&a[i]);
    ll ans=0;
    rep(i,0,(1<<n)){
        int tp=bitcnt(i)&1;
        ll ts=s;
        rep(j,0,n) if(i&(1<<j)) ts-=(a[j]+1);
        if(ts<0) continue;
        if(tp&1) ans=(ans-C(n+ts-1,n-1)+mod)%mod;
        else ans=(ans+C(n+ts-1,n-1))%mod;
       /// cout<<i<<" "<<C(n+ts-1,n-1)<<endl;
    }
    cout<<ans<<endl;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值