use std::collections::BTreeMap; #[derive(Debug, Clone)] struct SegmentTree { n: usize, orgn: usize, unit: T, mem: Vec, operator: F } impl SegmentTree where T: std::fmt::Debug + Copy, F: Fn(T, T) -> T { fn new(n: usize, unit: T, operator: F) -> Self { let mut size = 1usize; while size < n { size *= 2; } Self { n: size, orgn: n, unit: unit, mem: vec![unit; size*2-1], operator: operator, } } fn find_closed(&self, l: usize, r: usize) -> T { self.find(l, r+1) } fn find(&self, l: usize, r: usize) -> T { self._find(l, r, 0, 0, self.n) } fn set(&mut self, pos: usize, val: T) { let mut pos = pos + self.n - 1; self.mem[pos] = val; while pos > 0 { pos = self._parent(pos); self.mem[pos] = (self.operator)(self.mem[self._left(pos)], self.mem[self._right(pos)]); } } fn get(&mut self, pos: usize) -> T { self.mem[pos + self.n - 1] } fn _find(&self, a: usize, b: usize, nodenum: usize, l: usize, r: usize) -> T { if r <= a || b <= l { return self.unit; } else if a <= l && r <= b { return self.mem[nodenum]; } let left = self._find(a, b, self._left(nodenum), l, (l+r)/2); let right = self._find(a, b, self._right(nodenum), (l+r)/2, r); (self.operator)(left, right) } fn _left(&self, k: usize) -> usize { 2*k+1 } fn _right(&self, k: usize) -> usize { 2*k+2 } fn _parent(&self, k: usize) -> usize { (k-1)/2 } } fn main() { let mut nq = String::new(); std::io::stdin().read_line(&mut nq).ok(); let nq: Vec = nq.trim().split_whitespace().map(|s| s.parse().unwrap()).collect(); let n = nq[0]; let q = nq[1]; let mut a = String::new(); std::io::stdin().read_line(&mut a).ok(); let a: Vec = a.trim().split_whitespace().map(|s| s.parse().unwrap()).collect(); let mut queries = (0..q).map(|i| { let mut temp = String::new(); std::io::stdin().read_line(&mut temp).ok(); let temp: Vec = temp.trim().split_whitespace().map(|s| s.parse().unwrap()).collect(); (temp[0]-1, temp[1]-1, temp[2], i) }) .collect::>(); let mut btreemap = BTreeMap::new(); for i in 0..n { btreemap.entry(a[i]).or_insert(vec![]).push(i); } let mut cntseg = SegmentTree::new(n, 0usize, |x, y| x + y); let mut valseg = SegmentTree::new(n, 0usize, |x, y| x + y); let mut result = vec![0usize; q]; queries.sort_by_key(|&(_,_,x,_)| x); for &(l, r, x, i) in queries.iter() { let mut used = vec![]; btreemap.range(..=x).for_each(|(&val, v)| { used.push(val); for &pos in v.iter() { cntseg.set(pos, 1); valseg.set(pos, val); } }); used.iter().for_each(|v| { btreemap.remove(v); }); result[i] += valseg.find_closed(l, r); result[i] += (r-l+1-cntseg.find_closed(l, r)) * x; } for &v in result.iter() { println!("{}", v); } }