D. Almost Identity Permutations(dp)

D. Almost Identity Permutations
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
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.

Examples
input
4 1
output
1
input
4 2
output
7
input
5 3
output
31
input
5 4
output
76

题意:一个长度为n,由1~n组成的p序列(pi != pj ,i != j)。问有多少组排列方式使得只有k个pi = i。

解题思路:如代码

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
typedef long long LL;

const int maxn = 1005;
LL dp[maxn][maxn];//dp[i][j]:长度为i,由1 ~ i组成的序列p(序列中数都不相同),满足只有j个pm = m的排列方式数.

void Init(){
    dp[4][4] = 1;
    dp[4][3] = 0;
    dp[4][2] = 6;
    dp[4][1] = 8;
    dp[4][0] = 9;
}

int main(){
    Init();
    LL n,k,sum = 0;
    scanf("%I64d %I64d",&n,&k);
    for(LL i = 5;i <= n;i++){
        for(LL j = 0;j <= i;j++){
            if(j == 0) dp[i][j] = (i - 1) * dp[i - 1][j] + dp[i - 1][1];
            else{
                dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j] * (i - 1 - j) + dp[i - 1][j + 1] * (j + 1);
            }
        }
    }
    for(int i = n - k;i <= n;i++){
        sum += dp[n][i];
    }
    printf("%I64d\n",sum);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值