Count permutations of 1..N whose Cartesian tree has total child-position gap score at most S, modulo a prime.
Hard8Dynamic programmingTreeCombinatoricsNo attempts yetTime limit5sMemory limit512 MBA sequence A of distinct integers determines exactly one Cartesian tree. A Cartesian tree is a tree that meets these four conditions.
The picture below is the Cartesian tree built from A=[9,3,7,1,8,12,10,20,15,18,5].

Let T be the Cartesian tree built from A. The score of T is computed as follows. For every node with two children, find the positions in A of the two child values and take the difference of those positions. The score of T is the sum of that difference over all such nodes.
In the picture the nodes with two children are 1, 3, 10, 15. The two children of node 1 are 3 and 5, which sit at positions 2 and 11 of A, so this node scores 11−2=9. The other three nodes score 2, 3 and 2, so the score of T is 9+2+3+2=16.
You are given N, S and MOD. There are N! permutations of the numbers 1 through N, and each permutation builds one Cartesian tree. Let X be the number of those trees whose score is at most S. Write a program that prints X modulo MOD.
The first line contains N, S and MOD, separated by spaces. (1≤N≤100, 0≤S≤100, 3≤MOD≤109, MOD is prime)
Print on the first line how many of the N! permutations build a tree whose score is at most S, modulo MOD.
For N=3, the permutations (2,1,3) and (3,1,2) score 2, and the other four permutations score 0.