## Editorial for SAC '22 Code Challenge 5 P3 - Querying Presents

Remember to use this editorial

**only**when stuck, and**not to copy-paste code from it**. Please be respectful to the problem author and editorialist.**Submitting an official solution before solving the problem yourself is a bannable offence.**Author:

##### Subtask 1

It suffices to loop through every possible permutation of students and increment a counter by if the current permutation assigns every number to a different number than its index.

**Time Complexity:**

##### Subtask 2

Realize that (through either OEIS or previous problems) this is counting derangements, which has the following recurrence:

for , where and

Compute this for each query (or precompute for ) while .

**Time Complexity:**

## Comments