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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章