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: maxcruickshanks

Subtask 1

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

Time Complexity: O(N!)

Subtask 2

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

!n=(n1)(!(n1)+!(n2)) for n2, where !0=1 and !1=0

Compute this for each query (or precompute for N106) while mod109+7.

Time Complexity: O(i=1TNi)


Comments

There are no comments at the moment.