結果

問題 No.789 範囲の合計
ユーザー simansiman
提出日時 2022-11-25 02:59:09
言語 Ruby
(3.3.0)
結果
AC  
実行時間 602 ms / 1,000 ms
コード長 1,111 bytes
コンパイル時間 200 ms
コンパイル使用メモリ 7,552 KB
実行使用メモリ 28,160 KB
最終ジャッジ日時 2024-04-09 02:49:15
合計ジャッジ時間 7,864 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 90 ms
12,160 KB
testcase_01 AC 86 ms
12,416 KB
testcase_02 AC 593 ms
24,448 KB
testcase_03 AC 479 ms
21,120 KB
testcase_04 AC 544 ms
25,344 KB
testcase_05 AC 561 ms
24,320 KB
testcase_06 AC 564 ms
24,448 KB
testcase_07 AC 460 ms
22,528 KB
testcase_08 AC 532 ms
28,160 KB
testcase_09 AC 522 ms
25,856 KB
testcase_10 AC 602 ms
23,168 KB
testcase_11 AC 548 ms
24,704 KB
testcase_12 AC 521 ms
25,472 KB
testcase_13 AC 86 ms
12,160 KB
testcase_14 AC 85 ms
12,288 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

N = gets.to_i
Q = N.times.map { gets.split.map(&:to_i) }

memo = Hash.new
values = []
Q.select { |t, _, _| t == 0 }.each do |t, x, y|
  values << x
end

values << Float::INFINITY
values.uniq!
values.sort!
values.each.with_index(1) do |v, idx|
  memo[v] = idx
end

bit = BinaryIndexTree.new(N + 2)
ans = 0

N.times do |i|
  if Q[i][0] == 0
    _, x, y = Q[i]
    idx = memo[x]
    bit.add(idx, y)
  else
    _, lv, rv = Q[i]
    l = values.bsearch_index { |v| v >= lv }
    r = values.bsearch_index { |v| v > rv }
    l += 1

    ans += bit.sum(0, r + 1) - bit.sum(0, l)
  end
end

puts ans
0