---
id: 842
title: "Codeforces 451E:Devu and Flowers 题解"
slug: codeforces-451e
lang: zh
date: 2019-02-22T20:46:55
date_gmt: 2019-02-22T12:46:55
modified: 2019-02-22T20:46:55
status: publish
password_protected: false
category: { name: Olympiad in Informatics, slug: oi }
tags: [OI, 组合, 组合数学, 多重集, 容斥]
original_url: https://kalorona.com/oi/codeforces-451edevu-and-flowers-题解/
archived: 2026-11-27
editor: classic
media: []
archive_notes:
  - "Body headings were <h1> in the original; demoted to level 2 so the page title is the only h1."
comments: []
---

## 主要思路

这道题需要多重集的知识，如果没有学习请看[这篇博客](../668-oi-combinatorics/index.html)的多重集部分。

很明显，题意要求我们求出多重集的组合数，且为“增强版组合数”。所以，我们根据公式，使用二进制分解的方法来求出即可。这是一道比较裸的多重集组合数问题。

## 代码

```cpp
// CF451E.cpp
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int mod = 1e9 + 7, MAX_N = 25;
ll arr[MAX_N], n, inv[MAX_N], m;
ll quick_power(ll bas, ll tim)
{
    ll ans = 1;
    while (tim)
    {
        if (tim & 1)
            ans = ans * bas % mod;
        bas = bas * bas % mod;
        tim >>= 1;
    }
    return ans;
}
ll C(ll a, ll b)
{
    if (a < 0 || b < 0 || a < b)
        return 0;
    a %= mod;
    if (a == 0 || b == 0)
        return 1;
    ll ans = 1;
    for (int i = 0; i < b; i++)
        ans = ans * (a - i) % mod;
    for (int i = 1; i <= b; i++)
        ans = ans * inv[i] % mod;
    return ans;
}
int main()
{
    scanf("%lld%lld", &n, &m);
    for (int i = 1; i <= n; i++)
        scanf("%lld", &arr[i]);
    inv[0] = 1;
    for (int i = 1; i < MAX_N; i++)
        inv[i] = quick_power(i, mod - 2);
    ll ans = 0;
    for (int stat = 0; stat < (1 << n); stat++)
        if (stat == 0)
            ans = (ans + C(n + m - 1, n - 1)) % mod;
        else
        {
            ll t = n + m, p = 0;
            for (int i = 0; i < n; i++)
                if ((stat >> i) & 1)
                    p++, t -= arr[i + 1];
            t -= (p + 1);
            if (p & 1)
                ans = (ans - C(t, n - 1)) % mod;
            else
                ans = (ans + C(t, n - 1)) % mod;
        }
    ans = (ans + mod) % mod;
    printf("%lld", ans);
    return 0;
}
```

source:Page 172，《算法竞赛进阶指南》李煜东著
