Codeforces 888D: Almost Identity Permutations(錯排公式,組合數)

A permutation \(p\) of size \(n\) is an array such that every integer from \(1\) to \(n\) occurs exactly once in this array.ios

Let's call a permutation an almost identity permutation iff there exist at least \(n - k\) indices \(i (1 ≤ *i* ≤ n)\) such that \(p_i = i\).c++

Your task is to count the number of almost identity permutations for given numbers \(n\) and \(k\).ide

Input

The first line contains two integers \(n\) and \(k\) \((4 ≤ n ≤ 1000, 1 ≤ k ≤ 4)\).this

Output

Print the number of almost identity permutations for given \(n\) and \(k\).spa

Examples

Inputcode

4 1ci

Outputinput

1it

Inputio

4 2

Output

7

Input

5 3

Output

31

Input

5 4

Output

76

題意

給出\(n\)的全排列,求有多少種排列,知足至少\(n-k\)個位置上的數和下標相同(下標從\(1\)開始)

思路

由於\(1\leq k\leq 4\),因此能夠將題意轉換一下:在\(n\)的全排列中,找到\(k\)個數,數和下標的值全都不相等

咱們能夠從\(n\)個數中,隨機選出\(k\)個數,讓這\(k\)個數全都沒有放在正確的位置上,選\(k\)個數,咱們能夠用組合數來求,而後用錯排公式來求有多少個數沒放在正確的位置上。

由於\(k\)只有四個值,直接計算錯排公式的值便可

最後將\(1\)\(k\)中的這些值加起來便可

代碼

#include <bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define ms(a,b) memset(a,b,sizeof(a))
const int inf=0x3f3f3f3f;
const ll INF=0x3f3f3f3f3f3f3f3f;
const int maxn=1e6+10;
const int mod=1e9+7;
const int maxm=1e3+10;
using namespace std;
ll C(int n,int m)
{
    ll fenmu=1LL;
    ll fenzi=1LL;
    for(int i=1;i<=m;i++)
    {
        fenmu=1LL*fenmu*(n-i+1);
        fenzi=1LL*fenzi*i;
    }
    return fenmu/fenzi;
}
int main(int argc, char const *argv[])
{
    #ifndef ONLINE_JUDGE
        freopen("in.txt", "r", stdin);
        freopen("out.txt", "w", stdout);
        srand((unsigned int)time(NULL));
    #endif
    ios::sync_with_stdio(false);
    cin.tie(0);
    int n,k;
    cin>>n>>k;
    ll ans=0;
    if(k>=1)
        ans+=1;
    if(k>=2)
        ans+=(n*(n-1)/2);
    if(k>=3)
        ans+=2*C(n,3);
    if(k>=4)
        ans+=9*C(n,4);
    cout<<ans<<endl;
    #ifndef ONLINE_JUDGE
        cerr<<"Time elapsed: "<<1.0*clock()/CLOCKS_PER_SEC<<" s."<<endl;
    #endif
    return 0;
}
相關文章
相關標籤/搜索