There are n children and m apples that will be distributed to them. Your task is to count the number of ways this can be done.
For example, if and , there are 6 ways: , , , , and .
Example:
Input: n = 3, m = 2
Output: 6
Approach
C++
#include <bits/stdc++.h>using namespace std;const long long MOD = 1e9 + 7;long long qexp(long long a, long long b, long long m){long long res = 1;while (b){if (b % 2)res = res * a % m;a = a * a % m;b /= 2;}return res;}vector<long long> fact;void precompute(int n){fact.assign(n + 1, 1);for (int i = 1; i <= n; i++)fact[i] = fact[i - 1] * i % MOD;}long long nCk(int n, int k){if (k < 0 || k > n)return 0;return fact[n] * qexp(fact[k], MOD - 2, MOD) % MOD * qexp(fact[n - k], MOD - 2, MOD) % MOD;}long long distributingApples(int n, int m){return nCk(n + m - 1, m);}int main(){int n = 3, m = 2;precompute(2e6);cout << distributingApples(n, m) << "\n";return 0;}
No comments:
Post a Comment