Find the Permutations [Uva 11077]

45 篇文章 0 订阅
5 篇文章 0 订阅

题目地址请点击——


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} 需要两次交换( 1 2 3 4), {4,2,3,1} 只需一次( 1 4), {2,3,4,1} 需要 3 次,而 {1,2,3,4} 本身一次都不需要。
给定 n k,统计有多少个排列至少需要交换 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.

输入包含多组数据。每组数据仅一行,包含两个整数 n k 1<=n<=21 0<=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 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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值