CodeForces 888D Almost Identity Permutations

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.

Input

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

Output

Print the number of almost identity permutations for given n 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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值