結果

問題 No.1604 Swap Sort:ONE
ユーザー simansiman
提出日時 2021-07-17 17:29:57
言語 Ruby
(3.3.0)
結果
AC  
実行時間 85 ms / 2,000 ms
コード長 796 bytes
コンパイル時間 174 ms
コンパイル使用メモリ 11,292 KB
実行使用メモリ 15,340 KB
最終ジャッジ日時 2023-09-21 10:54:49
合計ジャッジ時間 4,064 ms
ジャッジサーバーID
(参考情報)
judge13 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 79 ms
15,104 KB
testcase_01 AC 75 ms
15,332 KB
testcase_02 AC 74 ms
15,236 KB
testcase_03 AC 74 ms
15,160 KB
testcase_04 AC 75 ms
15,132 KB
testcase_05 AC 83 ms
15,060 KB
testcase_06 AC 79 ms
15,148 KB
testcase_07 AC 81 ms
15,280 KB
testcase_08 AC 79 ms
15,244 KB
testcase_09 AC 80 ms
15,080 KB
testcase_10 AC 83 ms
15,060 KB
testcase_11 AC 85 ms
15,084 KB
testcase_12 AC 81 ms
15,340 KB
testcase_13 AC 81 ms
15,076 KB
testcase_14 AC 81 ms
15,252 KB
testcase_15 AC 80 ms
15,328 KB
testcase_16 AC 80 ms
15,296 KB
testcase_17 AC 79 ms
15,292 KB
testcase_18 AC 79 ms
15,036 KB
testcase_19 AC 81 ms
15,280 KB
testcase_20 AC 78 ms
15,064 KB
testcase_21 AC 80 ms
15,076 KB
testcase_22 AC 78 ms
15,256 KB
testcase_23 AC 77 ms
15,036 KB
testcase_24 AC 75 ms
15,064 KB
testcase_25 AC 80 ms
15,248 KB
testcase_26 AC 78 ms
15,284 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
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 = gets.to_i
P = gets.split.map(&:to_i)

puts P.inversion_number
0