HDU 3664 Permutation Counting (DP)

Permutation Counting

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1593    Accepted Submission(s): 821


Problem Description
Given a permutation a1, a2, … aN of {1, 2, …, N}, we define its E-value as the amount of elements where ai > i. For example, the E-value of permutation {1, 3, 2, 4} is 1, while the E-value of {4, 3, 2, 1} is 2. You are requested to find how many permutations of {1, 2, …, N} whose E-value is exactly k.
 

Input
There are several test cases, and one line for each case, which contains two integers, N and k. (1 <= N <= 1000, 0 <= k <= N).
 

Output
Output one line for each case. For the answer may be quite huge, you need to output the answer module 1,000,000,007.
 

Sample Input
3 0 3 1
 

Sample Output
1 4
Hint
There is only one permutation with E-value 0: {1,2,3}, and there are four permutations with E-value 1: {1,3,2}, {2,1,3}, {3,1,2}, {3,2,1} 题意:
给你一个{1, 2, …, N} 的排列a1a2, …  aN,我们定义这个排列的E值为其中ai> i的元素的数量。例如,排列{1, 3, 2, 4} 的E值为1,{4, 3, 2, 1} 的 E值为2。请你找出{1, 2, …, N} 有多少个E值为k的排列。
解题思路:当时比赛时,一开始我一直想成跟置换个数的关系了,后来又考虑成找规律了。。。。。。。直到看完题解焕然大悟。 dp状态dp[i][j]表示表示前i个数组成的排列中E值为j的排列个数。考虑从一个{1,2,3.。。。n-1}的排列向{1,2,,,n}的排列的状态转移。考虑 新增的数字i的位置: 1)可以放在第n个位置,这样不改变原排列的E值,即dp[i][j]=dp[i-1][j] 2)还可以放在位置x(1<=x<n)的位置,将原来x上的数字换到第n个位置上,这时只要考虑ax与x的关系: (1)ax>x,被换到n则E值-1,n放到x位置则E值+1,故E值不变。对于dp[i-1][j],这样的x(满足ax>x)有 j 个,则dp[i][j]还包含dp[i][j]*j个情况 (2)ax<=x,被换到n则E值不变,n换到x位置则E值+1,对于dp[i-1][j],这样的x(满足ax<=x) 有(i-1)-(j-1) (自己想想为什么),所以 dp[i][j]还包含dp[i-1][j-1]*(i-j)个情况。 综上可以得到 dp[i][j]=dp[i-1][j]+dp[i-1][j]*j+dp[i-1][j-1]*(i-j) =dp[i-1][j]*(1+j)+dp[i-1][j-1]*(i-j) 附上AC代码:
<span style="font-size:18px;">#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long LL;
const int mod=1000000007;
LL dp[1005][1005];
int n,k;
void init()
{
    dp[0][0]=1;
    for(int i=1;i<1001;i++){
        dp[i][0]=1;
        for(int j=1;j<=i;j++)
        {
            dp[i][j]=(dp[i-1][j]*(j+1)+dp[i-1][j-1]*(i-j))%mod;//记得取mod
        }
    }
}
int main()
{
    init();
    while(~scanf("%d %d",&n,&k))
    {
        printf("%I64d\n",dp[n][k]);
    }
    return 0;
}</span>


发布了106 篇原创文章 · 获赞 5 · 访问量 5万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章