Caching Combinatorics

Recently Arya the little panda got a permutation of size $A$ as a birthday present from his parents…

Click here to read the complete problem statement.

If you need help solving this problem, mention your approach and ask specific questions. Please avoid sharing your code and asking the Community to figure out “what’s wrong”.