class BinaryIndexTree def initialize(size, init: 0) @values = Array.new(size, init) @size = size end # @param idx [Integer] # @param x [Numeric] def add(idx, x) raise 'Out of range reference' if @size <= idx idx += 1 while idx <= @size @values[idx - 1] += x idx += idx & -idx end end def sum(l, r) _sum(r) - _sum(l) end private def _sum(idx) res = 0 while idx > 0 res += @values[idx - 1] idx -= idx & -idx end res end end class Array def inversion_number n = size bit = BinaryIndexTree.new(n + 1) cnt = 0 n.times do |i| cnt += i - bit.sum(0, self[i]) bit.add(self[i], 1) end cnt end end N, M = gets.split.map(&:to_i) P = gets.split.map(&:to_i) num = P.inversion_number if M.even? && num.odd? puts -1 elsif num == 0 puts 0 else if M.even? k = (num + M - 1) / M puts k * M else diff = (M - num).abs if num <= M if diff.even? puts M else puts 2 * M end else k = (diff + M - 1) / M n_diff = (k * M - num).abs if n_diff.even? puts k * M else puts (k + 1) * M end end end end