結果

問題 No.913 木の燃やし方
ユーザー koba-e964koba-e964
提出日時 2021-09-29 22:00:38
言語 Rust
(1.77.0)
結果
WA  
実行時間 -
コード長 6,350 bytes
コンパイル時間 6,289 ms
コンパイル使用メモリ 162,404 KB
実行使用メモリ 14,524 KB
最終ジャッジ日時 2023-09-23 17:30:25
合計ジャッジ時間 19,527 ms
ジャッジサーバーID
(参考情報)
judge12 / judge11
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,376 KB
testcase_01 AC 1 ms
4,380 KB
testcase_02 AC 1 ms
4,384 KB
testcase_03 WA -
testcase_04 WA -
testcase_05 AC 3 ms
4,376 KB
testcase_06 WA -
testcase_07 AC 2 ms
4,376 KB
testcase_08 AC 162 ms
14,136 KB
testcase_09 WA -
testcase_10 WA -
testcase_11 WA -
testcase_12 AC 167 ms
14,460 KB
testcase_13 AC 163 ms
14,124 KB
testcase_14 AC 160 ms
13,672 KB
testcase_15 AC 158 ms
13,748 KB
testcase_16 WA -
testcase_17 WA -
testcase_18 WA -
testcase_19 AC 150 ms
14,500 KB
testcase_20 AC 145 ms
14,484 KB
testcase_21 WA -
testcase_22 WA -
testcase_23 WA -
testcase_24 AC 121 ms
14,416 KB
testcase_25 AC 111 ms
14,424 KB
testcase_26 AC 171 ms
14,440 KB
testcase_27 AC 174 ms
14,428 KB
testcase_28 AC 149 ms
14,516 KB
testcase_29 AC 146 ms
14,496 KB
testcase_30 AC 146 ms
14,416 KB
testcase_31 AC 155 ms
14,436 KB
testcase_32 AC 163 ms
14,420 KB
testcase_33 AC 169 ms
14,436 KB
testcase_34 AC 145 ms
14,424 KB
testcase_35 AC 142 ms
14,500 KB
testcase_36 AC 124 ms
14,468 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
use std::io::{Write, BufWriter};
// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes.by_ref().map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr,) => {};
    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

macro_rules! read_value {
    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };
    ($next:expr, $t:ty) => ($next().parse::<$t>().expect("Parse error"));
}

/**
 * Segment Tree. This data structure is useful for fast folding on intervals of an array
 * whose elements are elements of monoid I. Note that constructing this tree requires the identity
 * element of I and the operation of I.
 * Verified by: yukicoder No. 259 (http://yukicoder.me/submissions/100581)
 *              AGC015-E (http://agc015.contest.atcoder.jp/submissions/1461001)
 */
struct SegTree<I, BiOp> {
    n: usize,
    dat: Vec<I>,
    op: BiOp,
    e: I,
}

impl<I, BiOp> SegTree<I, BiOp>
    where BiOp: Fn(I, I) -> I,
          I: Copy {
    pub fn new(n_: usize, op: BiOp, e: I) -> Self {
        let mut n = 1;
        while n < n_ { n *= 2; } // n is a power of 2
        SegTree {n: n, dat: vec![e; 2 * n - 1], op: op, e: e}
    }
    /* ary[k] <- v */
    pub fn update(&mut self, idx: usize, v: I) {
        let mut k = idx + self.n - 1;
        self.dat[k] = v;
        while k > 0 {
            k = (k - 1) / 2;
            self.dat[k] = (self.op)(self.dat[2 * k + 1], self.dat[2 * k + 2]);
        }
    }
    /* [a, b) (note: half-inclusive)
     * http://proc-cpuinfo.fixstars.com/2017/07/optimize-segment-tree/ */
    pub fn query(&self, mut a: usize, mut b: usize) -> I {
        let mut left = self.e;
        let mut right = self.e;
        a += self.n - 1;
        b += self.n - 1;
        while a < b {
            if (a & 1) == 0 {
                left = (self.op)(left, self.dat[a]);
            }
            if (b & 1) == 0 {
                right = (self.op)(self.dat[b - 1], right);
            }
            a = a / 2;
            b = (b - 1) / 2;
        }
        (self.op)(left, right)
    }
}

/*
 * Online monotone minima dp. For example, monge dp can be efficiently computed
 * by online_dc.
 * Verified by: https://yukicoder.me/problems/no/705
 * submission: https://yukicoder.me/submissions/566775
 */
const INF: i64 = 1 << 60;

// Complexity: O(n log m + m) where n = r - l, m = b - a.
fn monotone_minima<F>(l: usize, r: usize, a: usize, b: usize,
                      lat: &mut [i64], realizer: &mut [usize],
                      cost_fun: &F)
where F: Fn(usize, usize) -> i64 {
    let n = r - l;
    let m = b - a;
    if n == 0 || m == 0 {
        return;
    }
    let mid = (a + b) / 2;
    let mut mi = (INF, n);
    for i in l..r {
        let cost = cost_fun(i, mid);
        mi = std::cmp::min(mi, (cost, i));
    }
    let idx = mi.1;
    assert!(l <= idx && idx < r);
    lat[mid] = std::cmp::min(lat[mid], mi.0);
    realizer[mid] = idx;
    monotone_minima(l, idx + 1, a, mid, lat, realizer, cost_fun);
    monotone_minima(idx, r, mid + 1, b, lat, realizer, cost_fun);
}

trait Bisect<T> {
    fn lower_bound(&self, val: &T) -> usize;
    fn upper_bound(&self, val: &T) -> usize;
}

impl<T: Ord> Bisect<T> for [T] {
    fn lower_bound(&self, val: &T) -> usize {
        let mut pass = self.len() + 1;
        let mut fail = 0;
        while pass - fail > 1 {
            let mid = (pass + fail) / 2;
            if &self[mid - 1] >= val {
                pass = mid;
            } else {
                fail = mid;
            }
        }
        pass - 1
    }
    fn upper_bound(&self, val: &T) -> usize {
        let mut pass = self.len() + 1;
        let mut fail = 0;
        while pass - fail > 1 {
            let mid = (pass + fail) / 2;
            if &self[mid - 1] > val {
                pass = mid;
            } else {
                fail = mid;
            }
        }
        pass - 1
    }
}

trait Change { fn chmax(&mut self, x: Self); fn chmin(&mut self, x: Self); }
impl<T: PartialOrd> Change for T {
    fn chmax(&mut self, x: T) { if *self < x { *self = x; } }
    fn chmin(&mut self, x: T) { if *self > x { *self = x; } }
}

fn calc(a: &[i64]) -> Vec<i64> {
    let n = a.len();
    let mut acc = vec![0; n + 1];
    for i in 0..n {
        acc[i + 1] = acc[i] + a[i];
    }
    let mut dp = vec![INF; n + 1];
    let mut realizer = vec![0; n + 1];
    monotone_minima(0, n, 0, n + 1, &mut dp, &mut realizer, &|i, j| {
        if i < j {
            let ii = i as i64;
            let jj = j as i64;
            ii * ii - acc[i] + jj * jj + acc[j] - 2 * ii * jj
        } else {
            INF / 2
        }
    });
    // eprintln!("{:?}", dp);
    // eprintln!("realizer = {:?}", realizer);
    // Find min {dp[j] | i in [realizer[j], j)} for each i
    let mut st = SegTree::new(n + 1, min, INF);
    for i in 0..n + 1 {
        st.update(i, dp[i]);
    }
    let mut ret = vec![0; n];
    for i in 0..n {
        let idx = realizer.upper_bound(&i);
        let tmp = st.query(i + 1, idx);
        ret[i] = tmp;
    }
    ret
}

fn main() {
    // In order to avoid potential stack overflow, spawn a new thread.
    let stack_size = 104_857_600; // 100 MB
    let thd = std::thread::Builder::new().stack_size(stack_size);
    thd.spawn(|| solve()).unwrap().join().unwrap();
}

fn solve() {
    let out = std::io::stdout();
    let mut out = BufWriter::new(out.lock());
    macro_rules! puts {($($format:tt)*) => (let _ = write!(out,$($format)*););}
    input! {
        n: usize,
        a: [i64; n],
    }
    let dp1 = calc(&a);
    let mut a = a;
    a.reverse();
    let mut dp2 = calc(&a);
    dp2.reverse();
    for i in 0..n {
        puts!("{}\n", min(dp1[i], dp2[i]));
    }
}
0