There are n children at a Christmas party, and each of them has brought a gift. The idea is that everybody will get a gift brought by someone else.
In how many ways can the gifts be distributed?
Example:
Input: n = 4
Output: 9
Approach
C++
#include <bits/stdc++.h>using namespace std;const long long MOD = 1e9 + 7;long long exponentiationWithMod(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, invf;void precompute(int n){fact.assign(n + 1, 1);for (int i = 1; i <= n; i++)fact[i] = fact[i - 1] * i % MOD;invf.assign(n + 1, 1);invf[n] = exponentiationWithMod(fact[n], MOD - 2, MOD);for (int i = n - 1; i > 0; i--)invf[i] = invf[i + 1] * (i + 1) % MOD;}long long nCk(int n, int k){if (k < 0 || k > n)return 0;return fact[n] * invf[k] % MOD * invf[n - k] % MOD;}long long christmasParty(int n){long long ans = 0;for (int i = 0; i <= n; i++){long long sign = (i % 2) ? -1 : 1;ans = (ans + sign * nCk(n, i) * fact[n - i]) % MOD;}if (ans < 0)ans += MOD;return ans;}int main(){int n = 4;precompute(1e6);cout << christmasParty(n) << "\n";return 0;}
No comments:
Post a Comment