|
| 1 | +/* |
| 2 | +PARTIAL DEARRANGEMENTS |
| 3 | +
|
| 4 | +A partial dearrangement is a dearrangement where some points are |
| 5 | +fixed. That is, given a number n and a number k, we need to find |
| 6 | +count of all such dearrangements of n numbers, where k numbers are |
| 7 | +fixed in their position. |
| 8 | +*/ |
| 9 | + |
| 10 | +import java.util.Scanner; |
| 11 | + |
| 12 | +class Partial_Dearrangement { |
| 13 | + |
| 14 | + public static int mod = 1000000007; |
| 15 | + |
| 16 | + public static int nCr(int n, int r, int mod) { |
| 17 | + if (n < r) { |
| 18 | + return -1; |
| 19 | + } |
| 20 | + // We create a pascal triangle. |
| 21 | + int Pascal[] = new int[r + 1]; |
| 22 | + Pascal[0] = 1; |
| 23 | + for (int i = 1; i <= r; i++) { |
| 24 | + Pascal[i] = 0; |
| 25 | + } |
| 26 | + |
| 27 | + // We use the known formula nCr = (n-1)C(r) + (n-1)C(r-1) |
| 28 | + // for computing the values. |
| 29 | + for (int i = 1; i <= n; i++) { |
| 30 | + int k = (i < r) ? (i) : (r); |
| 31 | + // we know, nCr = nC(n-r). Thus, at any point we only need min |
| 32 | + for (int j = k; j > 0; j--) { |
| 33 | + // of the two, so as to improve our computation time. |
| 34 | + Pascal[j] = (Pascal[j] + Pascal[j - 1]) % mod; |
| 35 | + } |
| 36 | + } |
| 37 | + return Pascal[r]; |
| 38 | + } |
| 39 | + |
| 40 | + public static int count(int n, int k) { |
| 41 | + if (k == 0) { |
| 42 | + if (n == 0) { |
| 43 | + return 1; |
| 44 | + } |
| 45 | + if (n == 1) { |
| 46 | + return 0; |
| 47 | + } |
| 48 | + return (n - 1) * (count(n - 1, 0) + count(n - 2, 0)); |
| 49 | + } |
| 50 | + return nCr(n, k, mod) * count(n - k, 0); |
| 51 | + } |
| 52 | + |
| 53 | + public static void main(String args[]) { |
| 54 | + int number; |
| 55 | + Scanner s = new Scanner(System.in); |
| 56 | + number = s.nextInt(); |
| 57 | + int k; |
| 58 | + k = s.nextInt(); |
| 59 | + int dearrangements = count(number, k); |
| 60 | + System.out.print("The number of partial dearrangements is " + dearrangements); |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +/* |
| 65 | +INPUT : n = 6 |
| 66 | + k = 3 |
| 67 | +OUTPUT: The number of partial dearrangements is 40 |
| 68 | +*/ |
0 commit comments