結果

問題 No.2382 Amidakuji M
ユーザー simansiman
提出日時 2023-07-19 10:58:51
言語 Ruby
(3.3.0)
結果
AC  
実行時間 523 ms / 2,000 ms
コード長 1,230 bytes
コンパイル時間 279 ms
コンパイル使用メモリ 11,920 KB
実行使用メモリ 30,356 KB
最終ジャッジ日時 2023-10-19 13:28:52
合計ジャッジ時間 7,331 ms
ジャッジサーバーID
(参考情報)
judge13 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 86 ms
16,108 KB
testcase_01 AC 88 ms
16,108 KB
testcase_02 AC 88 ms
16,108 KB
testcase_03 AC 250 ms
22,072 KB
testcase_04 AC 400 ms
26,724 KB
testcase_05 AC 129 ms
17,452 KB
testcase_06 AC 279 ms
22,764 KB
testcase_07 AC 198 ms
20,016 KB
testcase_08 AC 94 ms
16,164 KB
testcase_09 AC 353 ms
25,252 KB
testcase_10 AC 481 ms
29,124 KB
testcase_11 AC 217 ms
20,796 KB
testcase_12 AC 353 ms
25,544 KB
testcase_13 AC 83 ms
16,108 KB
testcase_14 AC 84 ms
16,108 KB
testcase_15 AC 84 ms
16,108 KB
testcase_16 AC 83 ms
16,108 KB
testcase_17 AC 83 ms
16,108 KB
testcase_18 AC 84 ms
16,108 KB
testcase_19 AC 516 ms
30,356 KB
testcase_20 AC 514 ms
30,356 KB
testcase_21 AC 523 ms
30,356 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
Main.rb:59: warning: ambiguous first argument; put parentheses or a space even after `-' operator
Syntax OK

ソースコード

diff #

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
0