#P1338. Calendar Doomsday Prediction

    ID: 14625 Type: Default 1000ms 256MiB

Calendar Doomsday Prediction

Calendar Doomsday Prediction

In the ancient fantasy land of Oriental Genshin, a magical calendar is used to record the days. The calendar elements are the numbers from \(1\) to \(n\). On the first day, the calendar displays the permutation \(1,2,\ldots,n\). Each subsequent day, the calendar automatically changes to the lexicographically next permutation if we interpret the permutation as a number in base \(n+1\) (i.e. the permutation with the smallest numeric value among the not-yet‐appeared ones).

An ancient prophecy foretells that when on some day the inversion count of the calendar reaches exactly \(m\), the world will meet its end. Here an inversion in a permutation \(a_1,a_2,\ldots,a_n\) is defined as a pair \((i,j)\) (with \(i a_j\).

Your task is to help the prophet predict the doomsday by determining the day number (its lexicographic rank among all \(n!\) permutations, starting at 1) on which the inversion count of the calendar is exactly \(m\). If no permutation of \(1 \ldots n\) has exactly \(m\) inversions, output \(-1\).

Note: The lexicographic order here is induced by interpreting each permutation as a number in base \(n+1\). For example, for \(n = 3\) the permutations in order are:

1,2,3   (0 inversions)  --- Day 1
1,3,2   (1 inversion)   --- Day 2
2,1,3   (1 inversion)   --- Day 3
2,3,1   (2 inversions)  --- Day 4
3,1,2   (2 inversions)  --- Day 5
3,2,1   (3 inversions)  --- Day 6

For instance, if the input is 3 1 then the smallest permutation with exactly 1 inversion is 1,3,2 which appears at day 2, so the output should be 2.

inputFormat

The input consists of a single line containing two integers \(n\) and \(m\) separated by a space, where \(1 \leq n \leq 12\) (for feasibility) and \(0 \leq m \leq \frac{n(n-1)}{2}\).

outputFormat

Output a single integer representing the day number (1-indexed) on which the calendar first displays a permutation with exactly \(m\) inversions. If no such permutation exists, output \(-1\).

sample

3 1
2