#!/usr/bin/ruby # sherlocks-array-merging-algorithm DEBUG = false @total = 0 @magic = 10 ** 9 + 7 def total_add(x) @total = (@total + x) % @magic end def perm(n, r) result = n 2.upto(r) do |i| result = result * (n - i + 1) end result end n = gets.strip.to_i m = gets.strip.split(' ').map(&:to_i) # find largest increasing run size = 1 1.upto(n - 1) do |i| break if m[i-1] > m[i] size = i + 1 end size.downto(1) do |s| # verify that this is always a valid size ok = true round = 1 while round * s < n next_block = m[round * s, s] # verify that next block is increasing 1.upto(next_block.length - 1) do |i| ok = false if next_block[i - 1] > next_block[i] end break if !ok round += 1 end next if !ok round -= 1 if m.length % s != 0 puts "size #{s} round #{round} rem #{m.length % s}" if DEBUG if round == 1 && m.length % s == 0 puts "add 1" if DEBUG total_add(1) else num = perm(s, s) ** (round - 1) num = num * perm(s, m.length % s) puts "num #{num}" if DEBUG total_add(num) end end puts @total