Codeforces 451E - Devu and Flowers 容斥原理

Devu and Flowers

如果不考虑限制答案为 C(s + n - 1, n - 1), 即把s个球分到n个箱子中,箱子可以为空的方案数。

壮压枚举几个超过了, 容斥一下。

#include<bits/stdc++.h>
#define LL long long
#define fi first
#define se second
#define mk make_pair
#define PLL pair<LL, LL>
#define PLI pair<LL, int>
#define PII pair<int, int>
#define SZ(x) ((int)x.size())
#define ull unsigned long long
using namespace std;

const int N = 1e6 + 7;
const int inf = 0x3f3f3f3f;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9 + 7;
const double eps = 1e-8;

int n;
LL s, f[20], ans;

LL fastPow(LL a, LL b) {
    LL ans = 1;
    while(b) {
        if(b & 1) ans = ans * a % mod;
        a = a * a % mod; b >>= 1;
    }
    return ans;
}

LL calc(LL n, LL m) {
    if(n < 0 || n < m) return 0;
    if(n == m || !m) return 1;
    LL a = n % mod, b = 1;
    for(int i = 1; i < m; i++)
        a = a * ((n - i) % mod) % mod, b = b * (i + 1) % mod;
    return a * fastPow(b, mod - 2) % mod;
}

int main() {
    cin >> n >> s;
    for(int i = 0; i < n; i++) cin >> f[i];
    for(int S = 0; S < (1 << n); S++) {
        LL ret = 0, op = 1;
        for(int i = 0; i < n; i++)
            if(S >> i & 1) ret += f[i] + 1, op = -op;
        ans = (ans + op * calc(s - ret + n - 1, n - 1) + mod) % mod;
    }
    cout << ans << "\n";
    return 0;
}

/*
*/

猜你喜欢

转载自www.cnblogs.com/CJLHY/p/10359321.html