Codeforces 554C Kyoya and Colored Balls 【dp + 组合数学】

题目链接:Codeforces 554C Kyoya and Colored Balls

C. Kyoya and Colored Balls
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i + 1 for all i from 1 to k - 1. Now he wonders how many different ways this can happen.

Input
The first line of input will have one integer k (1 ≤ k ≤ 1000) the number of colors.

Then, k lines will follow. The i-th line will contain ci, the number of balls of the i-th color (1 ≤ ci ≤ 1000).

The total number of balls doesn’t exceed 1000.

Output
A single integer, the number of ways that Kyoya can draw the balls from the bag as described in the statement, modulo 1 000 000 007.

Examples
input
3
2
2
1
output
3
input
4
1
2
3
4
output
1680
Note
In the first sample, we have 2 balls of color 1, 2 balls of color 2, and 1 ball of color 3. The three ways for Kyoya are:

1 2 1 2 3
1 1 2 2 3
2 1 1 2 3

题意:有k种颜色,每种颜色的球有c[i]个。要求第i种颜色涂完第i+1种颜色才可以涂完。问方案数。

看着很玄乎,推一下会发现是个大水题。
sum[i]记录前缀和。
定义:dp[i]为涂完前i种颜色的方案数,最后一个i显然是固定的。那我们考虑第i+1种颜色的涂法,它可以在sum[i]位置后面涂j(1 <= j <= c[i+1])个,那么在前面有sum[i]个空位,我们需要将c[i+1]-j个填到sum[i]个空位里,这是一个经典模型,方案数为C(sum[i] + c[i+1] - j - 1, c[i+1] - j)。

不过题目数据太水了,总数不超过1000,不用逆元都可以过。。。
AC代码:

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#include <iostream>
#define CLR(a, b) memset(a, (b), sizeof(a))
using namespace std;
typedef long long LL;
const int INF = 0x3f3f3f3f;
const int MAXN = 1e5 + 10;
const int MOD = 1e9 + 7;
void add(LL &x, LL y) { x += y; x %= MOD; }
LL dp[1010];
int sum[1010], c[1010];
LL fac[2000000+10];
LL pow_mod(LL a, LL n) {
    LL ans = 1LL;
    while(n) {
        if(n & 1LL) {
            ans = ans * a % MOD;
        }
        a = a * a % MOD;
        n >>= 1LL;
    }
    return ans;
}
LL C(int n, int m) {
    return fac[n] * pow_mod(fac[m], MOD-2) % MOD * pow_mod(fac[n-m], MOD-2) % MOD;
}
void getfac() {
    fac[0] = 1LL;
    for(int i = 1; i <= 2000008; i++) {
        fac[i] = fac[i-1] * i % MOD;
    }
}
int main()
{
    getfac(); int n;
    while(scanf("%d", &n) != EOF) {
        sum[0] = 0;
        for(int i = 1; i <= n; i++) {
            scanf("%d", &c[i]);
            sum[i] = sum[i-1] + c[i];
        }
        dp[1] = 1LL;
        for(int i = 2; i <= n; i++) {
            dp[i] = dp[i-1];
            for(int j = 1; j < c[i]; j++) {
                add(dp[i], dp[i-1] * C(sum[i-1] + c[i] - j - 1, c[i] - j) % MOD);
            }
            //cout << dp[i] << endl;
        }
        printf("%lld\n", dp[n]);
    }
    return 0;
}

你可能感兴趣的:(Codeforces 554C Kyoya and Colored Balls 【dp + 组合数学】)