Find the Permutations
Description [English]
Sorting is one of the most used operations in real life, where Computer Science comes into act. It is well-known that the lower bound of swap based sorting is nlog(n). It means that the best possible
sorting algorithm will take at least O(nlog(n)) swaps to sort a set of n integers. However, to sort a particular array of n integers, you can always find a swapping sequence of at most (n − 1) swaps, once you know the position of each element in the sorted sequence.
For example consider four elements <1 2 3 4>. There are 24 possible permutations and for all elements you know the position in sorted sequence.
If the permutation is <2 1 4 3>, it will take minimum 2 swaps to make it sorted. If the sequence is <2 3 4 1>, at least 3 swaps are required. The sequence <4 2 3 1> requires only 1 and the sequence <1 2 3 4> requires none. In this way, we can find the permutations of N distinct integers which will take at least K swaps to be sorted.
Description [Chinese]
给出
1
~
给定
n
和
Input
Each input consists of two positive integers N (1 ≤ N ≤ 21) and K (0 ≤ K < N) in a single line. Input is terminated by two zeros. There can be at most 250 test cases.
输入包含多组数据。每组数据仅一行,包含两个整数
n
和
输入结束标志为
n=k=0
。
Output
For each of the input, print in a line the number of permutations which will take at least K swaps.
对于每组数据,输出满足条件的排列数目。
Sample Input
3 1
3 0
3 2
0 0
Sample Output
3
1
2
Solution
我们首先要解决这样一个问题:
已知一个排列的长度为
n
,至少需要交换多少次才能使其变为
把这个排列看作一个置换,将其循环分解。
元素个数为
x
的循环,需要
所以设循环节为
y
,则需要
设
fx,y
表示
1
~
我们要保证这个排列必须要有
这
x−y
个循环节可以是这次才有的,即在
fx−1,y
个排列的基础上,将第
x
个元素放在其最后一个,将这个元素作为单独的一个循环。
这
所以,
Code
#include <iostream>
#include <cstdio>
#include <stdint.h>
#define ULL unsigned long long
using namespace std;
ULL n,k;
ULL f[30][30];
int main(){
for(ULL i=1;i<=21;i++){
f[i][0]=1;
for(ULL j=1;j<i;j++)f[i][j]=f[i-1][j]+f[i-1][j-1]*(i-1);
}
while(scanf("%llu%llu",&n,&k)!=EOF&&n)printf("%llu\n",f[n][k]);
return 0;
}