Description:
A permutation p of size n is an array such that every integer from 1 to n occurs exactly once in this array.
Let's call a permutation an almost identity permutation iff there exist at least n - k indices i (1 ≤ i ≤ n) such that pi = i.
Your task is to count the number of almost identity permutations for given numbers n and k.
The first line contains two integers n and k (4 ≤ n ≤ 1000, 1 ≤ k ≤ 4).
Print the number of almost identity permutations for given n and k.
4 1
1
4 2
7
5 3
31
5 4
76
题目大意:
给定一个长度为n的元素为1-n的排列, 求个数为n-k的当前元素下标与当前下标元素相同的排列个数。
(举个例子 4 1 。序列为 1 2 3 4 有4-1=3个元素在自己初始位置上, 那么它只有一种排列方法: 1 2 3 4。)
解题思路:
首先我们看到它的k只有4, 所以我们可以对k的值进行特殊判定。
当k=1时, 不同方案为1.理由见举例。当k=2时, 不同方案为1* Cn2。当k=3时, 不同方案为2*Cn3。 当k=4时, 不同方案为9*Cn1。因为题目问至少为k, 那么对于答案直接累加即可。 这里的1 4 9代表元素为2, 3, 4的错排数。
这里给出求排列中n个元素错排的公式: D(1)= 0, D(2)= 1, D(n)= (n- 1)*(D(n-1)+ D(n-2))
代码:
#include <iostream>
#include <sstream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iomanip>
#include <utility>
#include <string>
#include <cmath>
#include <vector>
#include <bitset>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>
using namespace std;
/*
*ios::sync_with_stdio(false);
*/
typedef long long ll;
typedef unsigned long long ull;
const int dir[5][2] = {0, 1, 0, -1, 1, 0, -1, 0, 0, 0};
const ll ll_inf = 0x7fffffff;
const int inf = 0x3f3f3f;
const int mod = 1000000;
const int Max = (int) 1e6;
ll arr[Max], n, k, ans;
int main() {
//freopen("input.txt", "r", stdin);
scanf("%lld %lld", &n, &k);
if (k == 1) {
ans = 1;
}
else if (k == 2) {
ans = 1 + (n * (n - 1) / 2);
}
else if (k == 3) {
ans = 1 + (n * (n - 1) * (n - 2)) / 3 + (n * (n - 1) / 2);
}
else if (k == 4) {
ll temp = 1, temp2 = 1;
for (int i = 0; i < 4; ++i) {
temp *= ((n - i));
temp2 *= (i + 1);
}
temp /= temp2;
ans = 1 + (n * (n - 1) * (n - 2)) / 3 + (n * (n - 1) / 2) + temp * 9;
}
printf("%lld\n", ans);
return 0;
}