Advertisement
Guest User

Untitled

a guest
Sep 26th, 2016
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.00 KB | None | 0 0
  1. #include<iostream>
  2. #include<cstdio>
  3. using namespace std;
  4.  
  5.  
  6. long long int derrangement(long long i)
  7. {
  8.     if(i == 1 || i==0) return 0;
  9.     if(i==2) return 1;
  10.  
  11.     return (i-1) * (derrangement(i-1) + derrangement(i-2));
  12.  
  13.  
  14. }
  15. long long int factorial(long long int n)
  16. {
  17.  if(n==0 || n==1) return 1;
  18.    long long sum = 1;
  19.    for(long long int i = 1; i<=n; i++) sum*=i;
  20.  
  21.    return sum;
  22.  
  23. }
  24. long long combination(long long int n, long long int r)
  25. {
  26.     long long int factN = factorial(n);
  27.     long long int factR = factorial(r);
  28.     long long int factNR = factorial(n-r);
  29.     return factN/(factNR*factR);
  30. }
  31. int main()
  32. {
  33.  
  34.  
  35.     //freopen("in.txt", "r", stdin);
  36.     //freopen("out.txt", "w+", stdout);
  37.     long long int a, b;
  38.     while(cin>>a>>b)
  39.     {
  40.  
  41.  
  42.         long long res = derrangement(a);
  43.         for(long long i=1;i<=b;i++)
  44.         {
  45.             res+=combination(a,i)*derrangement(a-i);
  46.         }
  47.         if(a==b) res++;
  48.         cout<<res<<endl;
  49.     }
  50.  
  51.  
  52.  
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement