結果

問題 No.1890 Many Sequences Sum Queries
ユーザー siman
提出日時 2022-06-19 00:38:03
言語 Ruby
(3.4.1)
結果
AC  
実行時間 449 ms / 2,000 ms
コード長 967 bytes
コンパイル時間 40 ms
コンパイル使用メモリ 7,552 KB
実行使用メモリ 12,928 KB
最終ジャッジ日時 2024-10-10 17:41:15
合計ジャッジ時間 5,666 ms
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 1
other AC * 25
権限があれば一括ダウンロードができます
コンパイルメッセージ
Main.rb:66: warning: ambiguous first argument; put parentheses or a space even after `-' operator
Syntax OK

ソースコード

diff #

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

B = []
C = []

A.each do |a|
  if C.empty?
    C << a
  else
    C << C.last + a
  end

  if B.empty?
    B << a * (1 + a) / 2
  else
    B << B.last + a * (1 + a) / 2
  end
end

def f(s)
  return -1 if B[-1] < s
  return 0 if B[0] >= s

  ok = N - 1
  ng = 0

  while (ok - ng).abs >= 2
    x = (ok + ng) / 2

    if B[x] >= s
      ok = x
    else
      ng = x
    end
  end

  ok
end

def g(s, a, offset = 0)
  return 1 if offset + 1 >= s

  ng = 1
  ok = a

  while (ok - ng).abs >= 2
    x = (ok + ng) / 2
    b = offset + x * (1 + x) / 2

    if b >= s
      ok = x
    else
      ng = x
    end
  end

  ok
end

S.each do |s|
  idx = f(s)

  if idx == -1
    puts -1
  else
    res = if idx == 0
            g(s, A[0])
          else
            g(s, A[idx], B[idx - 1])
          end

    if idx == 0
      puts res
    else
      puts C[idx - 1] + res
    end
  end
end
0