I found an interesting problem recently, which looks like this:
There is a dull sorting algorithm which takes the 1st number from an array, it finds an element which is lower by 1 than the 1st element (or it takes the highest element when there is no lower one), and puts it in the front. Cost of putting element with index x (counting from 0) in the front is equal to its index. It continues this process until the array is sorted. The task is to count the cost of sorting all the n! permutations of numbers from 1 to n. The answer might be big so the answer should be modulo m (n and m are given in the input)
Example:
Input (n,m): 3 40
Answer: 15
There are permutations of numbers from 1 to 3. The costs of sorting them are:
(1,2,3)->0
(1,3,2)->5
(2,1,3)->1
(2,3,1)->2
(3,1,2)->4
(3,2,1)->3
sum = 15
My program generates all the possible arrays and sorts them one by one. Its complexity is O(n!*n^2), which is way too high. I am stuck with all my thoughts and this brute force solution.
There are also some funny things I have discovered:
- When I have grouped the costs of sorting permutations by the quantity of those costs I am getting a strange figure: n=7 https://cdn.discordapp.com/attachments/503942261051228160/905511062546292807/unknown.png (Each row has 2 numbers x * y, and y spaces before them. x-cost of sort, y-number of permutations(1-n) that have cost of sort equal to y). The score is all the rows x*y summed up. I can provide this figure for other n's, if needed.
- It might be about fibonacci numbers, just a feeling.
- As you can see the figure from the 1. has a segment in which all the y's are the same. It starts at x=n^2-4n+3.
