結果

問題 No.694 square1001 and Permutation 3
ユーザー simansiman
提出日時 2023-06-27 16:02:28
言語 Ruby
(3.3.0)
結果
TLE  
(最新)
AC  
(最初)
実行時間 -
コード長 1,205 bytes
コンパイル時間 257 ms
コンパイル使用メモリ 11,364 KB
実行使用メモリ 85,832 KB
最終ジャッジ日時 2023-09-17 13:32:09
合計ジャッジ時間 18,455 ms
ジャッジサーバーID
(参考情報)
judge13 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 81 ms
15,184 KB
testcase_01 AC 80 ms
15,280 KB
testcase_02 AC 81 ms
15,044 KB
testcase_03 AC 83 ms
15,036 KB
testcase_04 AC 84 ms
15,052 KB
testcase_05 AC 86 ms
15,300 KB
testcase_06 AC 87 ms
15,176 KB
testcase_07 AC 1,869 ms
30,816 KB
testcase_08 AC 2,147 ms
43,084 KB
testcase_09 TLE -
testcase_10 AC 1,847 ms
30,804 KB
testcase_11 TLE -
testcase_12 TLE -
testcase_13 AC 81 ms
15,292 KB
権限があれば一括ダウンロードができます
コンパイルメッセージ
Syntax OK

ソースコード

diff #

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] + 1)
      bit.add(self[i], 1)
    end

    cnt
  end
end

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
A = N.times.map { gets.to_i }
B = A.uniq.sort

memo = Hash.new
B.each.with_index(1) do |b, i|
  memo[b] = i
end

C = A.map { |a| memo[a] }
counter = C.tally
RUI = [0]

C.uniq.sort.each do |c|
  cnt = counter[c]

  RUI << RUI.last + cnt
end

# pp C
ans = []
cnt = C.inversion_number
ans << cnt

0.upto(N - 2) do |i|
  c = C[i]
  small_num = RUI[c] - counter[c]
  big_num = N - small_num - counter[c]

  cnt += (big_num - small_num)
  ans << cnt
end

puts ans
0