結果

問題 No.742 にゃんにゃんにゃん 猫の挨拶
ユーザー simansiman
提出日時 2022-05-03 13:03:50
言語 Ruby
(3.3.0)
結果
AC  
実行時間 141 ms / 2,500 ms
コード長 798 bytes
コンパイル時間 935 ms
コンパイル使用メモリ 11,336 KB
実行使用メモリ 15,712 KB
最終ジャッジ日時 2023-09-15 09:18:23
合計ジャッジ時間 4,076 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 80 ms
15,032 KB
testcase_01 AC 79 ms
15,144 KB
testcase_02 AC 80 ms
15,028 KB
testcase_03 AC 79 ms
15,148 KB
testcase_04 AC 79 ms
15,012 KB
testcase_05 AC 79 ms
15,272 KB
testcase_06 AC 80 ms
15,016 KB
testcase_07 AC 82 ms
15,016 KB
testcase_08 AC 83 ms
15,060 KB
testcase_09 AC 79 ms
15,156 KB
testcase_10 AC 81 ms
15,120 KB
testcase_11 AC 140 ms
15,604 KB
testcase_12 AC 141 ms
15,712 KB
testcase_13 AC 82 ms
15,248 KB
testcase_14 AC 83 ms
15,276 KB
testcase_15 AC 83 ms
15,260 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
M = N.times.map { gets.to_i }

puts M.inversion_number
0