UV 11077-find the permutations (recurrence)

Source: Internet
Author: User
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;}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.