Find the Permutations
题目大意:有多少个排列至少交换k次变为n的全排。
不难发现,把一个序列变成全排的步数等于全排变为这个序列的步数
长度为l的循环需要交换l - 1次,且一组循环唯一对应一个序列,一个序列唯一对应一组循环
dp[i][j]为i的全排交换j次能得到的排列数,从i-1全排转移过来,考虑第i个数,要么单独一个循环,要么加入某个循环的某个位置并多交换一次,因此有
dp[i][j] = dp[i-1][j] + dp[i-1][j-1] * (i - 1)
注意ull
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include <algorithm> 6 #include <queue> 7 #include <vector> 8 #include <cmath> 9 #define min(a, b) ((a) < (b) ? (a) : (b)) 10 #define max(a, b) ((a) > (b) ? (a) : (b)) 11 #define abs(a) ((a) < 0 ? (-1 * (a)) : (a)) 12 inline void swap(long long &a, long long &b) 13 { 14 long long tmp = a;a = b;b = tmp; 15 } 16 inline void read(long long &x) 17 { 18 x = 0;char ch = getchar(), c = ch; 19 while(ch < ‘0‘ || ch > ‘9‘) c = ch, ch = getchar(); 20 while(ch <= ‘9‘ && ch >= ‘0‘) x = x * 10 + ch - ‘0‘, ch = getchar(); 21 if(c == ‘-‘) x = -x; 22 } 23 24 const long long INF = 0x3f3f3f3f; 25 26 unsigned long long dp[30][30], n, k; 27 28 int main() 29 { 30 //dp[i][j]表示最少交换j次才能得到排列1...i的排列个数 dp[i][j] = dp[i-1][j-1] + dp[i-1][j] * (i - 1) 31 dp[1][0] = 1; 32 for(register long long i = 2;i <= 22;++ i) 33 for(register long long j = 0;j < i;++ j) 34 if(!j) dp[i][j] = dp[i - 1][j]; 35 else dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1] * (i - 1); 36 while(scanf("%llu %llu", &n, &k) != EOF && n * n + k * k) 37 printf("%llu\n", dp[n][k]); 38 return 0; 39 }