CodeForces 888D Almost Identity Permutations

来源:互联网 发布:知行供应链 编辑:程序博客网 时间:2024/05/21 22:48

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 leastn - k indices i (1 ≤ i ≤ n) such thatpi = i.

Your task is to count the number of almost identity permutations for given numbersn and k.

Input

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

Output

Print the number of almost identity permutations for givenn and k.

Example
Input
4 1
Output
1
Input
4 2
Output
7
Input
5 3
Output
31
Input
5 4
Output
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;}

原创粉丝点击