combinatorics dp math *1600

Please click on ads to support us..

Python Code:

n, k = map(int, input().split())
ans = 0
for i in range(k+1):
	if (i==1):
		ans += 1
	elif (i==2):
		ans += (n*(n-1))/2
	elif (i==3):
		ans += 2*(n*(n-1)*(n-2))/6
	elif (i==4):
		ans += 9*(n*(n-1)*(n-2)*(n-3))/24
print(int(ans))

C++ Code:

#include <bits/stdc++.h>
using namespace std;

#define int long long

int ans = 0;

int nCr(int n, int r)
{
    int val = 1;

    for (int i = n; i >= n - r + 1; i--)
    {
        val *= i;
    }

    for (int i = 2; i <= r; i++)
    {
        val /= i;
    }

    return val;
}

void solve(int tc = 0)
{
    int n, k;
    cin >> n >> k;

    int cnt = 0;

    // The calculation of the derangement value of “N” is as follows
    // DN= N![1-1/1!+1/2!-1/3!…1/N!],

    // n = 2 Dn = 1
    // n = 3 Dn = 2
    // n = 4 Dn = 9

    if (k >= 2)
    {
        cnt += nCr(n, 2);
    }

    if (k >= 3)
    {
        // after selecting 3 elements
        // none of the 3 elements should be at their
        // correct position
        // let the elements be 4 5 6
        // so we can place 4 at
        // _ 4 _ which will become 6 4 5 or
        // _ _ 4 which will become 5 6 4
        cnt += 2 * nCr(n, 3);
    }

    if (k >= 4)
    {
        // to place the first element we have 3 options
        // now suppose we have placed the first element
        // at the incorrect position...now that leaves
        // us with one incorrect position (since first element
        // position is empty) and 2 correct positions
        // so we have 3 elements out of which we can place anyone
        // on the position of the first element and..and there is
        // only one way to arrange the other two...since both positions
        // are correct so we have total 3*3*1 = 9 ways
        cnt += 9 * nCr(n, 4);
    }

    cout << 1 + cnt << '\n';
}

int32_t main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    int tc = 1;
    // cin >> tc;

    for (int i = 1; i <= tc; i++)
    {
        // cout << "Case #" << i << ": ";
        solve();
    }

    return 0;
}


Comments

Submit
0 Comments
More Questions

53A - Autocomplete
1729G - Cut Substrings
805B - 3-palindrome
805C - Find Amir
676C - Vasya and String
1042B - Vitamins
1729F - Kirei and the Linear Function
25D - Roads not only in Berland
1694A - Creep
659F - Polycarp and Hay
1040A - Palindrome Dance
372A - Counting Kangaroos is Fun
1396B - Stoned Game
16A - Flag
1056A - Determine Line
670B - Game of Robots
1418C - Mortal Kombat Tower
1382B - Sequential Nim
1272C - Yet Another Broken Keyboard
808A - Lucky Year
1245A - Good ol' Numbers Coloring
58B - Coins
1041C - Coffee Break
507A - Amr and Music
1041D - Glider
1486A - Shifting Stacks
1389B - Array Walk
71B - Progress Bar
701A - Cards
545A - Toy Cars