Find the Permutations [Uva 11077]

来源:互联网 发布:mac支持的大型网游 编辑:程序博客网 时间:2024/05/24 03:20

题目地址请点击——


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 的一个排列,可以通过一系列的变换变成 {1,2,3,,n}。比如 {2,1,4,3} 需要两次交换(1234),{4,2,3,1} 只需一次(14),{2,3,4,1} 需要 3 次,而 {1,2,3,4} 本身一次都不需要。
给定 nk,统计有多少个排列至少需要交换 k 次才能变成 {1,2,,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.

输入包含多组数据。每组数据仅一行,包含两个整数 nk1<=n<=210<=k<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,至少需要交换多少次才能使其变为 {1,2,,n}

把这个排列看作一个置换,将其循环分解。
元素个数为 x 的循环,需要 x1 次交换才能使其有序。
所以设循环节为 y,则需要 ny 次交换才能使整个排列有序。

fx,y 表示 1~x 的排列中至少需要交换 k 次才能有序的排列个数。

我们要保证这个排列必须要有 xy 个循环节。
xy 个循环节可以是这次才有的,即在 fx1,y 个排列的基础上,将第 x 个元素放在其最后一个,将这个元素作为单独的一个循环。

xy 个循环节可以是之前就有的,即在 fx1,y1 个排列的基础上,已经有了xy 个循环节,只需要将第 x 号元素随意放在某个循环的某个位置即可。

所以,

fx,y=fx1,y+fx1,y1(x1)fx,0=1


Code

#include <iostream>#include <cstdio>#include <stdint.h>#define ULL unsigned long longusing 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;}
1 0
原创粉丝点击