Table of Contents

ExplanationImplementation

Official Analysis

Explanation

We can iterate from 00 to kk and shuffle exactly kk positions of the permutation. After shuffling, exactly kk positions of the permutation should be different while the remaining positions remain the same to fulfill the almost identity criterion.

Let's consider how to count the ways to shuffle exactly mm positions of the permutation. First we need to choose exactly mm positions in the permutations out of nn indices which is (nm){n \choose m}. Now let’s consider how to shuffle the mm positions. We can consider permutations. However, in some permutations, all positions aren’t completely shuffled.

For example, if n=4n = 4.

The identity permutation will be 11 22 33 44.

Let’s say that we want to rearrange the first 3 elements.

One possible permutation is: 11 33 22 44.

In this permutation, the first element is still in this same place, which is not the desired outcome (we didn't shuffle all the elements we want to rearrange).

Thus, we need to find all permutations where all the elements are out of place. However, since k is relatively small, we can brute force permutations to find the number of valid permutations.

We can add the number of valid permutations multiplied by the number of ways to choose a permutation of that length.

Implementation

Time Complexity: O(NK)\mathcal{O}(NK)

C++

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
int n, k;
cin >> n >> k;

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!