The number of boys in the class is b = m - n. Since all boys are distinguishable, the number of ways to arrange them is
Around the boys, there are b + 1 positions where girls can be placed:
There are girls in total. Therefore, we need to choose distinct positions out of the b + 1 available positions in which to place the girls:
If n > b + 1, then the answer is .
The girls are also distinguishable, so they can be permuted.
Thus, the total number of ways to arrange all the students in a row is equal to
Example
Consider the test case m = 3, n = 2.
The number of boys is b = m - n = 3 - 2 = 1. The answer is equal to
Consider the test case m = 4, n = 2.
The number of boys is b = m - n = 4 - 2 = 2. The answer is equal to
Algorithm implementation
Let us define the arrays:
, which stores the factorials of numbers modulo ,
factinv, which stores the modular inverses of these factorials modulo :
#define MAX 1000001
#define MOD 1000000007
ll fact[MAX], factinv[MAX];The function pow computes the power of a number modulo a given modulus:
ll pow(ll x, ll n, ll p)
{
if (n == 0) return 1;
if (n % 2 == 0) return pow((x * x) % p, n / 2, p);
return (x * pow(x, n - 1, p)) % p;
}The inverse function finds the number that is the modular inverse of with respect to a prime modulo . Since is a prime number, by Fermat's Little Theorem the following holds:
This can be rewritten as (x \cdot x^{p - 2})~mod~p = 1, from which it follows that the modular inverse of is x^{p - 2}~mod~p.
ll inverse(ll x, ll p)
{
return pow(x, p - 2, p);
}The Cnk function computes the binomial coefficient using the formula:
ll Cnk(int n, int k)
{
return ((fact[n] * factinv[k]) % MOD * factinv[n - k]) % MOD;
}The main part of the program. Fill the arrays of factorials and inverse factorials factinv.
fact[0] = 1;
for (i = 1; i < MAX; i++)
fact[i] = (fact[i - 1] * i) % MOD;
factinv[0] = 1;
for (i = 1; i < MAX; i++)
factinv[i] = inverse(fact[i], MOD);Read the number of test cases .
scanf("%d", &tests);
while (tests--)
{Read the data for the current test case.
scanf("%d %d", &m, &n);Compute the number of boys b = m - n.
b = m - n;Compute and print the answer using the formula:
res = ((fact[n] * fact[b]) % MOD * Cnk(b + 1, n)) % MOD;
printf("%lld\n", res);
}