题面如下:
题意简说:
给你一个整数
n
a
n
d
k
n\ and\ k
n and k
长度为
n
n
n 的所有全排列中, 有多少个全排列满足有
k
k
k 个位置 满足
a
i
≠
i
a_i \ne i
ai=i
思路:
*** 排列组合 + 错排***
从
n
个位置选
2
∼
k
个位置进行错排
从 n 个位置选 2\sim k 个位置 进行错排
从n个位置选2∼k个位置进行错排
AC代码:
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <cstring>
#include <cmath>
#include <map>
#include <queue>
#include <stack>
#define buff \
ios::sync_with_stdio(false); \
cin.tie(0);
#define int long long
//#define ll long long
#define PII pair<int, int>
#define px first
#define py second
using namespace std;
const int N = 1009;
int n, k;
int c[N][N], D[10];
// 错排公式 D[0]=1,D[1]=0,D[2]=1,D[n]=(n-1)*(D[n-1]+D[n-2]);
void init()
{
c[0][0] = c[1][0] = c[1][1] = 1;
for (int i = 2; i <= 1000; i++)
{
c[i][0] = 1;
for (int j = 1; j <= i && j <= 4; ++j)
c[i][j] = c[i - 1][j] + c[i - 1][j - 1];
}
D[0] = 1;
D[1] = 0;
D[2] = 1;
D[3] = 2;
D[4] = 9;
}
void solve()
{
init();
cin >> n >> k;
int ans = 1;
for (int i = 2; i <= k; i++)
ans += c[n][i] * (i - 1) * (D[i - 1] + D[i - 2]);
cout << ans << '\n';
}
signed main()
{
buff;
solve();
}