Find the Permutations

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. 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. 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

【题意】

给出1~n的一个排列,可以通过一系列的交换变成{1,2,…,n}。比如{2,1,4,3}需要两次交换。给定n和k,统计有多少个排列至少需要k次交换才能变成{1,2,…,n}。

【分析】

  先考虑一下怎么计算最少变换次数。

  显然,如果把它弄成x个循环的乘积,最少变换次数为n-x。

  问题变成了,给你n个数,分成n-x份的圆排列方案。这个方案刚好就是第一类斯特林数啊。

  所以很简单,用第一类斯特林数的方程求方案就行了。

 #include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define LL unsigned long long
#define Maxn LL s1[][]; void init()
{
memset(s1,,sizeof());
s1[][]=;
for(int i=;i<=;i++)
for(int j=;j<=;j++)
s1[i][j]=s1[i-][j-]+s1[i-][j]*(i-);
// printf("==%lld\n",s1[2][0]);
} int main()
{
init();
int n,k;
while()
{
scanf("%d%d",&n,&k);
if(n==&&k==) break;
printf("%llu\n",s1[n][n-k]);
}
return ;
}

注意要用unsigned long long ,还是看了别人的代码才知道的。。。不然会WA、。。。。

其实这题只是用了小小的置换的思想而已。

2017-01-11 19:16:56

最新文章

  1. 判断是否IPv6网络
  2. clickheat简介
  3. Mysql错误信息汇总
  4. shiro-web整合
  5. (转)Ratchet教程:Buttons组件
  6. 禁用backspace键的后退功能
  7. 网上图书商城项目学习笔记-037工具类之BaseServlet及统一中文编码
  8. cell函数总结
  9. VS2010每次编译都重新编译整个工程的解决方案
  10. angular-route 里面templeteUrl 动态加载
  11. (二)Harbor WEB的使用
  12. Java8部分新特性的学习
  13. 吃奶酪 洛谷 p1433
  14. H - Repeats (重复最多子串的次数)
  15. css , dl , dt , dd 的使用. calc
  16. vagrant 虚拟机中安装 lnamp 环境
  17. mysqli_query数据库有数据,查不出来
  18. 20145236《网络对抗》Exp1 逆向及Bof基础
  19. 循序渐进学.Net Core Web Api开发系列【9】:常用的数据库操作
  20. java rmi 入门实例

热门文章

  1. 【BZOJ1598】牛跑步 [A*搜索]
  2. 【51NOD-0】1018 排序
  3. java分页通用篇
  4. Bagging和Boosting 概念及区别(转)
  5. Python模块学习 - openpyxl
  6. 开源网络准入系统(open source Network Access Control system)
  7. Redis 3.0 编译安装
  8. C#比较两个list集合,两集合同时存在或A集合存在B集合中无
  9. 【uva11613】生产销售规划
  10. leetcode之Ransom Note