結果

問題 No.2332 Make a Sequence
ユーザー koba-e964koba-e964
提出日時 2023-05-31 00:13:59
言語 Rust
(1.77.0)
結果
AC  
実行時間 197 ms / 2,000 ms
コード長 6,827 bytes
コンパイル時間 3,273 ms
コンパイル使用メモリ 158,124 KB
実行使用メモリ 23,052 KB
最終ジャッジ日時 2023-08-28 01:18:33
合計ジャッジ時間 16,985 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 1 ms
4,376 KB
testcase_01 AC 1 ms
4,380 KB
testcase_02 AC 1 ms
4,380 KB
testcase_03 AC 1 ms
4,376 KB
testcase_04 AC 1 ms
4,500 KB
testcase_05 AC 1 ms
4,380 KB
testcase_06 AC 1 ms
4,376 KB
testcase_07 AC 125 ms
21,096 KB
testcase_08 AC 43 ms
5,012 KB
testcase_09 AC 101 ms
14,368 KB
testcase_10 AC 101 ms
19,480 KB
testcase_11 AC 67 ms
11,840 KB
testcase_12 AC 155 ms
23,052 KB
testcase_13 AC 155 ms
23,032 KB
testcase_14 AC 155 ms
22,936 KB
testcase_15 AC 154 ms
23,048 KB
testcase_16 AC 153 ms
23,044 KB
testcase_17 AC 155 ms
23,028 KB
testcase_18 AC 154 ms
23,000 KB
testcase_19 AC 155 ms
23,016 KB
testcase_20 AC 154 ms
23,016 KB
testcase_21 AC 154 ms
23,028 KB
testcase_22 AC 154 ms
22,992 KB
testcase_23 AC 155 ms
23,040 KB
testcase_24 AC 154 ms
23,024 KB
testcase_25 AC 154 ms
22,988 KB
testcase_26 AC 154 ms
23,016 KB
testcase_27 AC 155 ms
23,044 KB
testcase_28 AC 154 ms
23,012 KB
testcase_29 AC 155 ms
22,952 KB
testcase_30 AC 154 ms
22,952 KB
testcase_31 AC 155 ms
23,020 KB
testcase_32 AC 155 ms
23,004 KB
testcase_33 AC 155 ms
23,024 KB
testcase_34 AC 156 ms
23,028 KB
testcase_35 AC 156 ms
23,024 KB
testcase_36 AC 153 ms
23,024 KB
testcase_37 AC 157 ms
22,936 KB
testcase_38 AC 156 ms
23,032 KB
testcase_39 AC 156 ms
23,024 KB
testcase_40 AC 156 ms
23,000 KB
testcase_41 AC 152 ms
23,028 KB
testcase_42 AC 162 ms
23,016 KB
testcase_43 AC 161 ms
23,016 KB
testcase_44 AC 160 ms
23,024 KB
testcase_45 AC 154 ms
23,028 KB
testcase_46 AC 162 ms
23,032 KB
testcase_47 AC 197 ms
22,936 KB
testcase_48 AC 197 ms
23,036 KB
testcase_49 AC 195 ms
22,940 KB
testcase_50 AC 196 ms
22,948 KB
testcase_51 AC 196 ms
23,028 KB
testcase_52 AC 156 ms
23,016 KB
testcase_53 AC 155 ms
22,996 KB
testcase_54 AC 154 ms
23,012 KB
testcase_55 AC 156 ms
22,996 KB
testcase_56 AC 155 ms
22,956 KB
testcase_57 AC 155 ms
22,948 KB
testcase_58 AC 155 ms
23,000 KB
testcase_59 AC 154 ms
23,012 KB
testcase_60 AC 155 ms
23,004 KB
testcase_61 AC 155 ms
23,024 KB
testcase_62 AC 182 ms
23,032 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

use std::cmp::*;
// 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"));
}

// Z algorithm. Calculates an array a[i] = |lcp(s, &s[i..])|,
// where s is the given slice.
// If n = s.length(), the returned array has length n + 1.
// E.g. z_algorithm(b"ababa") = vec![5, 0, 3, 0, 1, 0]
// Reference: http://snuke.hatenablog.com/entry/2014/12/03/214243
// Verified by: ABC284-F (https://atcoder.jp/contests/abc284/submissions/38752029)
fn z_algorithm<T: PartialEq>(s: &[T]) -> Vec<usize> {
    let n = s.len();
    let mut ret = vec![0; n + 1];
    ret[0] = n;
    let mut i = 1; let mut j = 0;
    while i < n {
        while i + j < n && s[j] == s[i + j] { j += 1; }
        ret[i] = j;
        if j == 0 { i += 1; continue; }
        let mut k = 1;
        while i + k < n && k + ret[k] < j {
            ret[i + k] = ret[k];
            k += 1;
        }
        i += k; j -= k;
    }
    ret
}

// Li-Chao segment tree for min.
// Ref: https://judge.yosupo.jp/submission/17300 by niuez
// Verified by: https://judge.yosupo.jp/problem/segment_add_get_min (https://judge.yosupo.jp/submission/125824)
pub type LCTCoord = i64;
pub struct MinLiChaoSegTree {
    n: usize, // size of this Li-Chao segment tree
    xs: Box<[LCTCoord]>, // the coordinates associated to 0..n
    dat: Box<[(LCTCoord, LCTCoord)]>,
    e: (LCTCoord, LCTCoord), // identity for min
}

impl MinLiChaoSegTree {
    #[inline(always)]
    fn of((a, b): (LCTCoord, LCTCoord), x: LCTCoord) -> LCTCoord {
        a * x + b
    }
    // Initializes a Li-Chao segment tree with given coordinates and an identity for min.
    pub fn new(xs: &[LCTCoord], e: (LCTCoord, LCTCoord)) -> Self {
        assert!(!xs.is_empty());
        let n = xs.len().next_power_of_two();
        let mut xs = xs.to_vec();
        xs.resize(n, *xs.last().unwrap());
        MinLiChaoSegTree {
            n: n,
            xs: xs.into_boxed_slice(),
            dat: vec![e; 2 * n].into_boxed_slice(),
            e: e,
        }
    }
    // O(log n)
    fn add_range(&mut self, mut idx: usize, mut l: usize, mut r: usize, mut added: (LCTCoord, LCTCoord)) {
        let n = self.n;
        while idx < 2 * n {
            let m = (l + r) >> 1;
            let cur = self.dat[idx];
            let bl = Self::of(cur, self.xs[l]) > Self::of(added, self.xs[l]);
            let bm = Self::of(cur, self.xs[m]) > Self::of(added, self.xs[m]);
            let br = Self::of(cur, self.xs[r - 1]) > Self::of(added, self.xs[r - 1]);
            if bm {
                std::mem::swap(&mut self.dat[idx], &mut added);
            }
            if bl == br {
                // self.dat[idx] <= added for xs[l] <= x < xs[r]. No extra work needed.
                break;
            }
            if bl != bm {
                //        l m r
                // added: - + +
                // cur  : + - -
                // Recurses into [l, m).
                idx <<= 1;
                r = m; 
            } else {
                //        l m r
                // added: + + -
                // cur  : - - +
                // Recurses into [m, r).
                idx = 2 * idx + 1;
                l = m;
            }
        }
    }
    // lct.add_line((a, b)) adds a line y = ax + b.
    // O(log n)
    #[inline(always)]
    #[allow(unused)]
    pub fn add_line(&mut self, line: (LCTCoord, LCTCoord)) {
        self.add_range(1, 0, self.n, line);
    }
    // lct.add_seg(l..r, (a, b)) adds a segment y = ax + b, xs[l] <= x < xs[r].
    // O(log^2 n)
    pub fn add_seg(&mut self, rng: std::ops::Range<usize>, line: (LCTCoord, LCTCoord)) {
        let (mut l, mut r) = (rng.start, rng.end);
        debug_assert!(l <= r && r <= self.n);
        if l == r { return; }
        let mut li = l + self.n;
        let mut ri = r + self.n;
        let mut len = 1;
        while li < ri {
            if (li & 1) != 0 {
                self.add_range(li, l, l + len, line);
                li += 1;
                l += len;
            }
            if (ri & 1) != 0 {
                ri -= 1;
                self.add_range(ri, r - len, r, line);
                r -= len;
            }
            li >>= 1;
            ri >>= 1;
            len <<= 1;
        }
    }
    // lct.get(x) gets the minimum value of the lines added so far at xs[x].
    // O(log n)
    pub fn get(&self, x: usize) -> LCTCoord {
        let mut idx = x + self.n;
        let x = self.xs[x];
        let mut res = Self::of(self.e, x);
        while idx > 0 {
            let cur = Self::of(self.dat[idx], x);
            if cur < res {
                res = cur;
            }
            idx >>= 1;
        }
        res
    }
}

// https://yukicoder.me/problems/no/2332 (3)
// L(l) := lcp(B[l..], A) の長さ とする。(Z-algorithm で前計算をすれば O(1) 時間で計算できる。)
// dp[l+u].chmin(dp[l] + C_l * u) (1 <= u <= L(l)) という DPを考えると、これはイベントの管理を行えば実行できる。
// もらう DP をする。Li-Chao tree で以下のイベントの処理ができれば良い。
// 1. x = i における線分たちの最小値を取得する。
// 2. 線分 i <= x <= i + L(i), y = C_i * (x - i) + dp[i] を追加する。
// 計算量は O(N + M log^2 M)
fn main() {
    input! {
        n: usize, m: usize,
        a: [u32; n],
        b: [u32; m],
        c: [i64; m],
    }
    let mut cont = a.clone();
    cont.extend_from_slice(&b);
    let z = z_algorithm(&cont);
    let mut xs = vec![];
    for i in 0..m + 1 {
        xs.push(i as i64);
    }
    const INF: i64 = 1 << 50;
    let mut lct = MinLiChaoSegTree::new(&xs, (0, INF));
    let mut dp = vec![0; m + 1];
    for i in 0..m + 1 {
        if i > 0 {
            dp[i] = lct.get(i);
        }
        if i < m {
            let len = min(n, z[n + i]);
            lct.add_seg(i..i + len + 1, (c[i], dp[i] - c[i] * i as i64));
        }
    }
    println!("{}", if dp[m] >= INF { -1 } else { dp[m] });
}
0