zoukankan      html  css  js  c++  java
  • UVA

    Sorting is one of the most usedoperations in real life, where Computer Science comes into act. It iswell-known that the lower bound of swap based sorting is nlog(n).It means that the best possible sorting algorithm will take at least W(nlog(n))swaps to sort a set of nintegers. However, to sort a particular array of n integers, you can alwaysfind a swapping sequence of at most (n-1) swaps, once you know theposition of each element in the sorted sequence. For example – consider fourelements <1 2 3 4>. There are 24 possible permutations and for allelements you know the position in sorted sequence.

    If the permutation is <2 1 43>, 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 31> requires only 1 and the sequence <1 2 3 4> requires none. In thisway, we can find the permutations of Ndistinct integers which will take at least K swaps to be sorted.

    Input

    Each input consists of two positiveintegers N (1≤N≤21) and K (0≤K<N) in a single line. Inputis terminated by two zeros. There can be at most 250 test cases.

    Output

    For each of the input, print in aline the number of permutations which will take at least K swaps.

    SampleInput                             Output for Sample Input

    3 1

    3 0

    3 2

    0 0

     

    3

    1

    2

     


    Problemsetter: Md. Kamruzzaman

    Special Thanks: Abdullah-al-Mahmud

     题意:给出一个1-n的排列。能够通过一系列的置换变成{1,2,3...n},给定n和k。统计有多少个排列须要交换k次才干变成{1,2,3..n}

    思路:我们能够把排列p理解成一个置换,而且分解成循环,则各循环之间独立,且c个元素的循环须要交换c-1次,设f[i][j]表示至少须要交换j次才干变成{1,2....i}的排列个数,则f[i][j] = f[i-1][j] + f[i-1][j-1]*(i-1)。由于元素i要么自己形成一个循环,要么增加前两随意一个循环的任何位置

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    typedef unsigned long long ull;
    using namespace std;
    const int maxn = 30;
    
    ull f[maxn][maxn];
    
    int main() {
    	memset(f, 0, sizeof(f));
    	f[1][0] = 1;
    	for (int i = 2; i <= 21; i++) 
    		for (int j = 0; j < i; j++) {
    			f[i][j] += f[i-1][j];
    			if (j)
    				f[i][j] += f[i-1][j-1] * (i-1);
    		} 
    
    	int n, k;
    	while (scanf("%d%d", &n, &k) != EOF && n) {
    		printf("%llu
    ", f[n][k]);
    	}
    	return 0;
    }


  • 相关阅读:
    这一次,Google 终于对 Web 自动化下手了!
    移动端自动化 AutoJS 快速入门指南
    App 端自动化的最佳方案,完全解放双手!
    快过年了,如何使用 AutoJS 自动化快速抢微信红包!
    字节面试问我如何高效设计一个LRU,当场懵
    当前大厂笔试最高频的十道算法题
    coding game, 边打游戏边学编程,是一种怎么样的体验?
    一文详解面试常考的TopK问题
    动态规划,这几个问题最常见!
    备战蓝桥杯,你可以这么准备
  • 原文地址:https://www.cnblogs.com/yangykaifa/p/7106797.html
Copyright © 2011-2022 走看看