結果

問題 No.2169 To Arithmetic
ユーザー akakimidoriakakimidori
提出日時 2022-12-21 04:42:46
言語 Rust
(1.77.0 + proconio)
結果
AC  
実行時間 178 ms / 2,000 ms
コード長 8,397 bytes
コンパイル時間 15,531 ms
コンパイル使用メモリ 380,504 KB
実行使用メモリ 13,952 KB
最終ジャッジ日時 2024-11-18 02:34:40
合計ジャッジ時間 18,197 ms
ジャッジサーバーID
(参考情報)
judge1 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
5,248 KB
testcase_01 AC 1 ms
5,248 KB
testcase_02 AC 2 ms
5,248 KB
testcase_03 AC 1 ms
5,248 KB
testcase_04 AC 2 ms
5,248 KB
testcase_05 AC 3 ms
5,248 KB
testcase_06 AC 3 ms
5,248 KB
testcase_07 AC 2 ms
5,248 KB
testcase_08 AC 2 ms
5,248 KB
testcase_09 AC 36 ms
5,248 KB
testcase_10 AC 84 ms
9,524 KB
testcase_11 AC 84 ms
7,984 KB
testcase_12 AC 59 ms
7,740 KB
testcase_13 AC 119 ms
11,572 KB
testcase_14 AC 63 ms
6,948 KB
testcase_15 AC 70 ms
8,896 KB
testcase_16 AC 62 ms
6,828 KB
testcase_17 AC 109 ms
8,464 KB
testcase_18 AC 56 ms
5,376 KB
testcase_19 AC 178 ms
13,736 KB
testcase_20 AC 174 ms
13,732 KB
testcase_21 AC 177 ms
13,732 KB
testcase_22 AC 176 ms
13,736 KB
testcase_23 AC 171 ms
13,736 KB
testcase_24 AC 74 ms
12,160 KB
testcase_25 AC 87 ms
8,340 KB
testcase_26 AC 80 ms
12,928 KB
testcase_27 AC 83 ms
13,952 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

use std::io::Write;

fn run() {
    input! {
        n: usize,
        q: usize,
        a: [i64; n],
        d: [i64; q],
    }
    let mut b = a.windows(2).map(|a| a[1] - a[0]).collect::<Vec<_>>();
    let mut sb = b.clone();
    b.sort();
    let mut sum = b.clone();
    sum.insert(0, 0);
    sb.insert(0, 0);
    for i in 1..sum.len() {
        sum[i] += sum[i - 1];
        sb[i] += sb[i - 1];
    }
    let mut cht = IncrementalCHT::new();
    for i in 0..sb.len() {
        let a = -(i as i64) + (n - 1 - i) as i64;
        let b = sb[i] - (sb[n - 1] - sb[i]);
        cht.add_line(-a, -b);
    }
    let out = std::io::stdout();
    let mut out = std::io::BufWriter::new(out.lock());
    for d in d {
        let pos = b.upper_bound(&d);
        let l = pos as i64 * d - sum[pos];
        let r = sum[n - 1] - sum[pos] - (n - 1 - pos) as i64 * d;
        let need = -cht.find(d);
        let ans = need + (l + r - need) / 2;
        writeln!(out, "{}", ans).ok();
    }
}

fn main() {
    run();
}

// ---------- begin input macro ----------
// reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
#[macro_export]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

#[macro_export]
macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

#[macro_export]
macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, bytes) => {
        read_value!($iter, String).bytes().collect::<Vec<u8>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}
// ---------- end input macro ----------
// ---------- begin super slice ----------
pub trait SuperSlice {
    type Item;
    fn lower_bound(&self, key: &Self::Item) -> usize
    where
        Self::Item: Ord;
    fn lower_bound_by<F>(&self, f: F) -> usize
    where
        F: FnMut(&Self::Item) -> std::cmp::Ordering;
    fn lower_bound_by_key<K, F>(&self, key: &K, f: F) -> usize
    where
        K: Ord,
        F: FnMut(&Self::Item) -> K;
    fn upper_bound(&self, key: &Self::Item) -> usize
    where
        Self::Item: Ord;
    fn upper_bound_by<F>(&self, f: F) -> usize
    where
        F: FnMut(&Self::Item) -> std::cmp::Ordering;
    fn upper_bound_by_key<K, F>(&self, key: &K, f: F) -> usize
    where
        K: Ord,
        F: FnMut(&Self::Item) -> K;
    fn next_permutation(&mut self) -> bool
    where
        Self::Item: Ord;
    fn next_permutation_by<F>(&mut self, f: F) -> bool
    where
        F: FnMut(&Self::Item, &Self::Item) -> std::cmp::Ordering;
    fn prev_permutation(&mut self) -> bool
    where
        Self::Item: Ord;
}

impl<T> SuperSlice for [T] {
    type Item = T;
    fn lower_bound(&self, key: &Self::Item) -> usize
    where
        T: Ord,
    {
        self.lower_bound_by(|p| p.cmp(key))
    }
    fn lower_bound_by<F>(&self, mut f: F) -> usize
    where
        F: FnMut(&Self::Item) -> std::cmp::Ordering,
    {
        self.binary_search_by(|p| f(p).then(std::cmp::Ordering::Greater))
            .unwrap_err()
    }
    fn lower_bound_by_key<K, F>(&self, key: &K, mut f: F) -> usize
    where
        K: Ord,
        F: FnMut(&Self::Item) -> K,
    {
        self.lower_bound_by(|p| f(p).cmp(key))
    }
    fn upper_bound(&self, key: &Self::Item) -> usize
    where
        T: Ord,
    {
        self.upper_bound_by(|p| p.cmp(key))
    }
    fn upper_bound_by<F>(&self, mut f: F) -> usize
    where
        F: FnMut(&Self::Item) -> std::cmp::Ordering,
    {
        self.binary_search_by(|p| f(p).then(std::cmp::Ordering::Less))
            .unwrap_err()
    }
    fn upper_bound_by_key<K, F>(&self, key: &K, mut f: F) -> usize
    where
        K: Ord,
        F: FnMut(&Self::Item) -> K,
    {
        self.upper_bound_by(|p| f(p).cmp(key))
    }
    fn next_permutation(&mut self) -> bool
    where
        T: Ord,
    {
        self.next_permutation_by(|a, b| a.cmp(b))
    }
    fn next_permutation_by<F>(&mut self, mut f: F) -> bool
    where
        F: FnMut(&Self::Item, &Self::Item) -> std::cmp::Ordering,
    {
        use std::cmp::Ordering::*;
        if let Some(x) = self.windows(2).rposition(|a| f(&a[0], &a[1]) == Less) {
            let y = self.iter().rposition(|b| f(&self[x], b) == Less).unwrap();
            self.swap(x, y);
            self[(x + 1)..].reverse();
            true
        } else {
            self.reverse();
            false
        }
    }
    fn prev_permutation(&mut self) -> bool
    where
        T: Ord,
    {
        self.next_permutation_by(|a, b| a.cmp(b).reverse())
    }
}
// ---------- end super slice ----------
// 以下のクエリを処理する
//   add_line(a, b): 直線 ax + b を追加
//   find(x): min (ax + b) を返す。空のとき呼ぶとREになる
// 計算量
// 直線追加クエリがN回飛んでくるとする
// 直線追加 償却O(log N)
// 点質問: O((log N)^2)
// ---------- begin incremental convex hull trick (min) ----------
// reference: https://yukicoder.me/wiki/decomposable_searching_problem
// verify: https://old.yosupo.jp/submission/35150
#[derive(Clone)]
struct ConvexHullTrick {
    line: Vec<(i64, i64)>,
}

impl ConvexHullTrick {
    fn new(mut line: Vec<(i64, i64)>) -> Self {
        assert!(line.len() > 0);
        line.sort();
        line.dedup_by(|a, b| a.0 == b.0);
        let mut stack: Vec<(i64, i64)> = vec![];
        for (a, b) in line {
            while stack.len() >= 2 {
                let len = stack.len();
                let (c, d) = stack[len - 1];
                let (e, f) = stack[len - 2];
                let x = (d - b).div_euclid(a - c);
                let y = (f - d).div_euclid(c - e);
                if x >= y {
                    stack.pop();
                } else {
                    break;
                }
            }
            stack.push((a, b));
        }
        ConvexHullTrick { line: stack }
    }
    fn find(&self, x: i64) -> i64 {
        let mut l = 0;
        let mut r = self.line.len() - 1;
        let line = &self.line;
        let func = |k: usize| -> i64 {
            let (a, b) = line[k];
            a * x + b
        };
        while r - l >= 3 {
            let ll = (2 * l + r) / 3;
            let rr = (l + 2 * r) / 3;
            if func(ll) <= func(rr) {
                r = rr;
            } else {
                l = ll;
            }
        }
        line[l..=r].iter().map(|p| p.0 * x + p.1).min().unwrap()
    }
}

#[derive(Clone, Default)]
pub struct IncrementalCHT {
    size: usize,
    cht: Vec<(ConvexHullTrick, usize)>,
}

impl IncrementalCHT {
    pub fn new() -> Self {
        IncrementalCHT { 
            size: 0,
            cht: vec![]
        }
    }
    pub fn add_line(&mut self, a: i64, b: i64) {
        self.size += 1;
        let mut line = vec![(a, b)];
        let mut p = 0;
        while self.cht.last().map_or(false, |q| q.1 == p) {
            p += 1;
            line.append(&mut self.cht.pop().unwrap().0.line);
        }
        let cht = ConvexHullTrick::new(line);
        self.cht.push((cht, p));
    }
    pub fn find(&self, x: i64) -> i64 {
        self.cht.iter().map(|p| p.0.find(x)).min().unwrap()
    }
    pub fn append(&mut self, other: &mut Self) {
        if self.size < other.size {
            std::mem::swap(self, other);
        }
        for (mut cht, _) in other.cht.drain(..) {
            for (a, b) in cht.line.drain(..) {
                self.add_line(a, b);
            }
        }
        other.size = 0;
    }
}
// ---------- end incremental convex hull trick (min) ----------
0