2014
11-30

# Permutation Counting

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.

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

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

3 0
3 1

1
4

HintThere 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} 

/*

递推。
f[i][j]=①(f[i-1][j])+②(j*f[i-1][j])+③(f[i-1][j-1]*(i-j))，

2012-05-10
*/

#include"stdio.h"
__int64 f[1011][1011];
int main()
{
int i,l;
int n,k;
f[1][0]=1;
f[1][1]=0;
for(i=2;i<=1000;i++)
{
f[i][0]=1;
f[i][i]=0;
for(l=1;l<i;l++)
{
f[i][l]=f[i-1][l]+l*f[i-1][l]+f[i-1][l-1]*(i-l);
f[i][l]%=1000000007;
}
}

while(scanf("%d%d",&n,&k)!=-1)	printf("%d\n",f[n][k]);

return 0;
}

1. a是根先忽略掉，递归子树。剩下前缀bejkcfghid和后缀jkebfghicd，分拆的原则的是每个子树前缀和后缀的节点个数是一样的，根节点出现在前缀的第一个，后缀的最后一个。根节点b出现后缀的第四个位置，则第一部分为四个节点，前缀bejk，后缀jkeb，剩下的c出现在后缀的倒数第2个，就划分为cfghi和 fghic，第3部分就为c、c

2. 约瑟夫也用说这么长……很成熟的一个问题了，分治的方法解起来o(n)就可以了，有兴趣可以看看具体数学的第一章，关于约瑟夫问题推导出了一系列的结论，很漂亮