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, Q = gets.split.map(&:to_i) A = gets.split.map.with_index(1) { |v, i| [i, v.to_i] } A.sort_by! { |_, a| -a } queries = Q.times.map { |i| [i] + gets.split.map(&:to_i) } queries.sort_by! { |_, _, _, _, x| -x } ans = Array.new(Q, 0) cnt = 0 bit_sum = BinaryIndexTree.new(N + 2) bit_cnt = BinaryIndexTree.new(N + 2) queries.each do |i, _, l, r, x| while A.size >= 1 && A[0][-1] >= x idx, a = A.shift bit_sum.add(idx, a) bit_cnt.add(idx, 1) end cnt = bit_cnt.sum(l, r + 1) sum = bit_sum.sum(l, r + 1) ans[i] = sum - cnt * x # pp [:cnt, cnt, :l, l, :r, r] end puts ans