結果

問題 No.3078 Difference Sum Query
ユーザー urectanc
提出日時 2025-03-28 22:47:47
言語 Rust
(1.83.0 + proconio)
結果
AC  
実行時間 77 ms / 2,000 ms
コード長 2,420 bytes
コンパイル時間 13,753 ms
コンパイル使用メモリ 402,680 KB
実行使用メモリ 17,396 KB
最終ジャッジ日時 2025-03-28 22:48:08
合計ジャッジ時間 17,596 ms
ジャッジサーバーID
(参考情報)
judge1 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 26
権限があれば一括ダウンロードができます

ソースコード

diff #

use std::cmp::Reverse;

use proconio::{input, marker::Usize1};

fn main() {
    input! {
        n: usize, q: usize,
        a: [usize; n],
        queries: [(Usize1, usize, usize); q]
    }

    let mut cum = vec![0; n + 1];
    for (i, &a) in a.iter().enumerate() {
        cum[i + 1] = cum[i] + a;
    }

    let mut a = a.into_iter().enumerate().collect::<Vec<_>>();
    a.sort_unstable_by_key(|&(_, a)| Reverse(a));

    let mut queries = queries.into_iter().enumerate().collect::<Vec<_>>();
    queries.sort_unstable_by_key(|&(_, (_, _, x))| x);

    let mut ans = vec!["".to_string(); q];
    let mut bit_cnt = BinaryIndexedTree::new(n, 0);
    let mut bit_val = BinaryIndexedTree::new(n, 0);
    for (i, (l, r, x)) in queries {
        while a.last().map_or(false, |&(_, a)| a < x) {
            let (j, a) = a.pop().unwrap();
            bit_cnt.add(j, 1);
            bit_val.add(j, a);
        }

        let mut res = (cum[r] - cum[l]) as isize - x as isize * (r - l) as isize;
        let cnt = bit_cnt.sum(l, r) as isize;
        let val = bit_val.sum(l, r) as isize;
        res += 2 * (cnt * x as isize - val);

        ans[i] = res.to_string();
    }

    println!("{}", ans.join("\n"));
}

pub struct BinaryIndexedTree<T> {
    n: usize,
    array: Vec<T>,
    e: T,
}

impl<T> BinaryIndexedTree<T>
where
    T: Clone + std::ops::AddAssign + std::ops::Sub<Output = T> + std::cmp::PartialOrd,
{
    pub fn new(n: usize, e: T) -> Self {
        Self {
            n,
            array: vec![e.clone(); n + 1],
            e,
        }
    }

    pub fn add(&mut self, i: usize, x: T) {
        let mut i = i + 1;
        while i <= self.n {
            self.array[i] += x.clone();
            i += i & i.wrapping_neg();
        }
    }

    pub fn cum(&self, mut i: usize) -> T {
        let mut cum = self.e.clone();
        while i > 0 {
            cum += self.array[i].clone();
            i -= i & i.wrapping_neg();
        }
        cum
    }

    pub fn sum(&self, l: usize, r: usize) -> T {
        self.cum(r) - self.cum(l)
    }

    pub fn lower_bound(&self, mut x: T) -> usize {
        let mut i = 0;
        let mut k = 1 << (self.n.next_power_of_two().trailing_zeros());
        while k > 0 {
            if i + k <= self.n && self.array[i + k] < x {
                x = x - self.array[i + k].clone();
                i += k;
            }
            k >>= 1;
        }
        i
    }
}
0