Ultraviolet A 11077-find the permutations
Question Link
Given N and K, find the number of sequences containing elements [1-N] and exchange K times to obtain a sequence of [1, 2, 3... n ].
Idea: recursive DP [I] [J] indicates that J times are required for each element. When an element is added, the number of times it is added to the End remains unchanged, and the number of times in other positions is + 1, this can be proved. There are several cycles in the original sequence, and the required number of times is the sum of the loops with a length of-1. Then, a new element is added to form a loop with itself at the end, the number of times remains unchanged, and the rest of the positions will be added to other cycles. The number of times is + 1, so the recurrence isDP(I,J) =DP(I? 1,J? 1 )? (I? 1) +DP(I? 1,J)
Code:
#include <stdio.h>#include <string.h>const int N = 22;int n, k;unsigned long long dp[N][N];int main() {dp[1][0] = 1;for (unsigned long long i = 2; i <= 21; i++) {for (int j = 0; j < i; j++) {dp[i][j] = dp[i - 1][j];if (j) dp[i][j] += dp[i - 1][j - 1] * (i - 1); }}while (~scanf("%d%d", &n, &k) && n || k) {printf("%llu\n", dp[n][k]); }return 0;}