D. Almost Identity Permutations(dp)

来源:互联网 发布:ios移动网络下上传图片 编辑:程序博客网 时间:2024/06/06 06:31

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);}