結果
| 問題 |
No.409 ダイエット
|
| コンテスト | |
| ユーザー |
ngtkana
|
| 提出日時 | 2021-12-21 21:26:33 |
| 言語 | Rust (1.83.0 + proconio) |
| 結果 |
AC
|
| 実行時間 | 399 ms / 2,000 ms |
| コード長 | 20,747 bytes |
| コンパイル時間 | 15,073 ms |
| コンパイル使用メモリ | 379,732 KB |
| 実行使用メモリ | 29,872 KB |
| 最終ジャッジ日時 | 2024-09-15 15:38:48 |
| 合計ジャッジ時間 | 27,417 ms |
|
ジャッジサーバーID (参考情報) |
judge4 / judge6 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 92 |
コンパイルメッセージ
warning: unused imports: `Leaf`, `Tuple`, `VecLen`
--> src/main.rs:360:27
|
360 | multi_token::{Leaf, Parser, ParserTuple, RawTuple, Tuple, VecLen},
| ^^^^ ^^^^^ ^^^^^^
|
= note: `#[warn(unused_imports)]` on by default
warning: unused import: `with_str`
--> src/main.rs:598:35
|
598 | pub use self::i::{with_stdin, with_str};
| ^^^^^^^^
warning: unused imports: `ParserTuple`, `Parser`, `RawTuple`, `Token`, `Usize1`
--> src/main.rs:600:28
|
600 | pub use super::i::{Parser, ParserTuple, RawTuple, Token, Usize1};
| ^^^^^^ ^^^^^^^^^^^ ^^^^^^^^ ^^^^^ ^^^^^^
ソースコード
use cht_integer::{Concave, ConvexHullTrick, X};
#[allow(unused_imports)]
#[cfg(feature = "dbg")]
use dbg::lg;
use crate::cht_integer::Quadratic;
fn main() {
let mut buf = ngtio::with_stdin();
let n = buf.usize();
let a = buf.i64();
let b = buf.i64();
let w = buf.i64();
let d = buf.vec::<i64>(n);
let mut cht = ConvexHullTrick::<Concave>::new();
cht.add(2 * Quadratic::from(w) - 2 * a * X + b * X * (X + 1));
for (i, &d) in d.iter().enumerate() {
let i = i as i64;
let value = cht.eval(i) + 2 * d;
cht.add(value - 2 * a * (X - i - 1) + b * (X - 1 - i) * (X - i));
}
let ans = cht.eval(n as i64) / 2;
println!("{}", ans);
}
// cht_integer {{{
#[allow(dead_code)]
mod cht_integer {
use std::{
borrow::Borrow,
collections::BTreeSet,
fmt::Debug,
i64::{MAX, MIN},
marker::PhantomData,
ops::{Add, Mul, Sub},
};
pub trait ConvexOrConcave {}
pub enum Convex {}
pub enum Concave {}
impl ConvexOrConcave for Convex {}
impl ConvexOrConcave for Concave {}
#[derive(Clone, Debug, Default, Hash, PartialEq)]
pub struct ConvexHullTrick<C: ConvexOrConcave> {
base: ConvexHullTrickBase,
coeff_at_two: i64,
__marker: PhantomData<fn(C) -> C>,
}
impl ConvexHullTrick<Convex> {
pub fn new() -> Self {
Self {
base: Default::default(),
coeff_at_two: 0,
__marker: PhantomData,
}
}
pub fn multieval(&self, xs: impl Iterator<Item = i64>) -> Vec<i64> {
xs.map(|x| self.eval(x)).collect()
}
pub fn collect_lines(&self) -> Vec<(i64, i64)> {
self.base
.set
.iter()
.map(|&seg| (seg.line.p, -seg.line.q))
.collect()
}
pub fn eval(&self, x: i64) -> i64 {
self.base.eval(x) + self.coeff_at_two * x * x
}
pub fn add(&mut self, quadratic: Quadratic) {
let Quadratic([zeroth, first, second]) = quadratic;
if self.base.set.is_empty() {
self.coeff_at_two = second;
} else {
assert_eq!(
self.coeff_at_two, second,
"added a expression with different `second` from the before.",
)
}
self.base.insert(first, zeroth)
}
}
impl ConvexHullTrick<Concave> {
pub fn new() -> Self {
Self {
base: Default::default(),
coeff_at_two: 0,
__marker: PhantomData,
}
}
pub fn multieval(&self, xs: impl Iterator<Item = i64>) -> Vec<i64> {
xs.map(|x| self.eval(x)).collect()
}
pub fn collect_lines(&self) -> Vec<(i64, i64)> {
self.base
.set
.iter()
.map(|&seg| (-seg.line.p, seg.line.q))
.collect()
}
pub fn eval(&self, x: i64) -> i64 {
-self.base.eval(x) + self.coeff_at_two * x * x
}
pub fn add(&mut self, quadratic: Quadratic) {
let Quadratic([zeroth, first, second]) = quadratic;
if self.base.set.is_empty() {
self.coeff_at_two = second;
} else {
assert_eq!(
self.coeff_at_two, second,
"added a expression with different `second` from the before.",
)
}
self.base.insert(-first, -zeroth)
}
}
#[derive(Clone, Debug, Default, Hash, PartialEq)]
struct ConvexHullTrickBase {
set: BTreeSet<Segment>,
}
impl ConvexHullTrickBase {
fn eval(&self, x: i64) -> i64 {
assert!(
!self.set.is_empty(),
"empty maximum is the negative infinity"
);
self.set.range(Max(x)..).next().unwrap().line.eval(x)
}
fn lave(&self, p: i64) -> Option<i64> {
assert!(
!self.set.is_empty(),
"empty maximum is the negative infinity"
);
let &Segment {
line: Line { p: p1, q: q1 },
min: Min(min),
max: _,
} = self.set.range(p..).next()?;
if min == MIN {
if p1 == p {
Some(q1)
} else {
None
}
} else {
Some(q1 - (p1 - p) * min)
}
}
pub fn insert(&mut self, tilt: i64, intercept: i64) {
let q = -intercept;
let p = tilt;
if !self.set.is_empty() && self.lave(p).map_or(false, |c| c <= q) {
return;
}
self.set.take(&p);
let line = Line { p, q };
while let Some(&seg1) = self.set.range(..p).next_back() {
if seg1.min.0 == MIN || line.eval(seg1.min.0) < seg1.line.eval(seg1.min.0) {
break;
}
self.set.remove(&seg1);
}
while let Some(&seg1) = self.set.range(p..).next() {
if seg1.max.0 == MAX || line.eval(seg1.max.0) < seg1.line.eval(seg1.max.0) {
break;
}
self.set.remove(&seg1);
}
if let Some(&seg1) = self.set.range(..p).next_back() {
self.set.remove(&seg1);
match seg1.line.brace(line) {
Err(x) => {
debug_assert!(seg1.min.0 < x);
self.set.insert(Segment {
max: Max(x),
..seg1
});
}
Ok(brace) => {
if seg1.min.0 < brace.min.0 {
self.set.insert(Segment {
max: Max(brace.min.0),
..seg1
});
}
self.set.insert(brace);
}
}
}
if let Some(&seg1) = self.set.range(p..).next() {
self.set.remove(&seg1);
match line.brace(seg1.line) {
Err(x) => {
debug_assert!(x < seg1.max.0);
self.set.insert(Segment {
min: Min(x),
..seg1
});
}
Ok(brace) => {
if brace.max.0 < seg1.max.0 {
self.set.insert(Segment {
min: Min(brace.max.0),
..seg1
});
}
self.set.insert(brace);
}
}
}
let min = Min(self
.set
.range(..p)
.next_back()
.map_or(MIN, |seg1| seg1.max.0));
let max = Max(self.set.range(p..).next().map_or(MAX, |seg1| seg1.min.0));
if min.0 < max.0 {
self.set.insert(Segment { line, min, max });
}
}
}
pub const X: Quadratic = Quadratic([0, 1, 0]);
#[derive(Clone, Debug, Default, Hash, PartialEq, Copy)]
pub struct Quadratic([i64; 3]);
impl Quadratic {
pub fn eval(self, x: i64) -> i64 {
self.0[0] + (self.0[1] + self.0[2] * x) * x
}
}
impl From<i64> for Quadratic {
fn from(x: i64) -> Self {
Self([x, 0, 0])
}
}
impl<T: Into<Self>> Add<T> for Quadratic {
type Output = Self;
fn add(self, rhs: T) -> Self::Output {
let rhs = rhs.into();
Self([
self.0[0] + rhs.0[0],
self.0[1] + rhs.0[1],
self.0[2] + rhs.0[2],
])
}
}
impl Add<Quadratic> for i64 {
type Output = Quadratic;
fn add(self, rhs: Quadratic) -> Self::Output {
rhs.add(self)
}
}
impl<T: Into<Self>> Sub<T> for Quadratic {
type Output = Self;
fn sub(self, rhs: T) -> Self::Output {
let rhs = rhs.into();
Self([
self.0[0] - rhs.0[0],
self.0[1] - rhs.0[1],
self.0[2] - rhs.0[2],
])
}
}
impl Sub<Quadratic> for i64 {
type Output = Quadratic;
fn sub(self, rhs: Quadratic) -> Self::Output {
let lhs: Quadratic = self.into();
Quadratic([
lhs.0[0] - rhs.0[0],
lhs.0[1] - rhs.0[1],
lhs.0[2] - rhs.0[2],
])
}
}
impl<T: Into<Self>> Mul<T> for Quadratic {
type Output = Self;
fn mul(self, rhs: T) -> Self::Output {
let rhs = rhs.into();
assert_eq!(self.0[1] * rhs.0[2] + self.0[2] * rhs.0[1], 0);
assert_eq!(self.0[2] * rhs.0[2], 0);
Self([
self.0[0] * rhs.0[0],
self.0[0] * rhs.0[1] + self.0[1] * rhs.0[0],
self.0[0] * rhs.0[2] + self.0[1] * rhs.0[1] + self.0[2] * rhs.0[0],
])
}
}
impl Mul<Quadratic> for i64 {
type Output = Quadratic;
fn mul(self, rhs: Quadratic) -> Self::Output {
rhs.mul(self)
}
}
#[derive(Clone, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord, Copy)]
struct Min(i64);
#[derive(Clone, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord, Copy)]
struct Max(i64);
#[derive(Clone, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord, Copy)]
struct Line {
p: i64,
q: i64,
}
impl Line {
fn eval(&self, x: i64) -> i64 {
self.p * x - self.q
}
fn brace(self, other: Self) -> Result<Segment, i64> {
let Self { p: p0, q: q0 } = self;
let Self { p: p1, q: q1 } = other;
debug_assert!(p0 < p1);
let x0 = (q1 - q0).div_euclid(p1 - p0);
if x0 * (p1 - p0) == (q1 - q0) {
return Err(x0);
}
let x1 = x0 + 1;
let p = (p1 * x1 - p0 * x0) - (q1 - q0);
let q = (p1 - p0) * x0 * x1 - q1 * x0 + q0 * x1;
debug_assert_eq!(p * x0 - q, p0 * x0 - q0);
debug_assert_eq!(p * x1 - q, p1 * x1 - q1);
Ok(Segment {
line: Self { p, q },
min: Min(x0),
max: Max(x1),
})
}
}
#[derive(Clone, Default, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Copy)]
struct Segment {
line: Line,
min: Min,
max: Max,
}
impl Borrow<i64> for Segment {
fn borrow(&self) -> &i64 {
&self.line.p
}
}
impl Borrow<Min> for Segment {
fn borrow(&self) -> &Min {
&self.min
}
}
impl Borrow<Max> for Segment {
fn borrow(&self) -> &Max {
&self.max
}
}
}
// }}}
// template {{{
#[cfg(not(feature = "dbg"))]
#[allow(unused_macros)]
#[macro_export]
macro_rules! lg {
($($expr:expr),*) => {};
}
#[allow(dead_code)]
mod ngtio {
mod i {
pub use self::{
multi_token::{Leaf, Parser, ParserTuple, RawTuple, Tuple, VecLen},
token::{Token, Usize1},
};
use std::{
io::{self, BufRead},
iter,
};
pub fn with_stdin() -> Tokenizer<io::BufReader<io::Stdin>> {
io::BufReader::new(io::stdin()).tokenizer()
}
pub fn with_str(src: &str) -> Tokenizer<&[u8]> {
src.as_bytes().tokenizer()
}
pub struct Tokenizer<S: BufRead> {
queue: Vec<String>, // FIXME: String のみにすると速そうです。
scanner: S,
}
macro_rules! prim_method {
($name:ident: $T:ty) => {
pub fn $name(&mut self) -> $T {
<$T>::leaf().parse(self)
}
};
($name:ident) => {
prim_method!($name: $name);
};
}
macro_rules! prim_methods {
($name:ident: $T:ty; $($rest:tt)*) => {
prim_method!($name:$T);
prim_methods!($($rest)*);
};
($name:ident; $($rest:tt)*) => {
prim_method!($name);
prim_methods!($($rest)*);
};
() => ()
}
impl<S: BufRead> Tokenizer<S> {
pub fn token(&mut self) -> String {
self.load();
self.queue.pop().expect("入力が終了したのですが。")
}
pub fn new(scanner: S) -> Self {
Self {
queue: Vec::new(),
scanner,
}
}
fn load(&mut self) {
while self.queue.is_empty() {
let mut s = String::new();
let length = self.scanner.read_line(&mut s).unwrap(); // 入力が UTF-8 でないときにエラーだそうです。
if length == 0 {
break;
}
self.queue = s.split_whitespace().rev().map(str::to_owned).collect();
}
}
pub fn skip_line(&mut self) {
assert!(
self.queue.is_empty(),
"行の途中で呼ばないでいただきたいです。現在のトークンキュー: {:?}",
&self.queue
);
self.load();
}
pub fn end(&mut self) {
self.load();
assert!(self.queue.is_empty(), "入力はまだあります!");
}
pub fn parse<T: Token>(&mut self) -> T::Output {
T::parse(&self.token())
}
pub fn parse_collect<T: Token, B>(&mut self, n: usize) -> B
where
B: iter::FromIterator<T::Output>,
{
iter::repeat_with(|| self.parse::<T>()).take(n).collect()
}
pub fn tuple<T: RawTuple>(&mut self) -> <T::LeafTuple as Parser>::Output {
T::leaf_tuple().parse(self)
}
pub fn vec<T: Token>(&mut self, len: usize) -> Vec<T::Output> {
T::leaf().vec(len).parse(self)
}
pub fn vec_tuple<T: RawTuple>(
&mut self,
len: usize,
) -> Vec<<T::LeafTuple as Parser>::Output> {
T::leaf_tuple().vec(len).parse(self)
}
pub fn vec2<T: Token>(&mut self, height: usize, width: usize) -> Vec<Vec<T::Output>> {
T::leaf().vec(width).vec(height).parse(self)
}
pub fn vec2_tuple<T>(
&mut self,
height: usize,
width: usize,
) -> Vec<Vec<<T::LeafTuple as Parser>::Output>>
where
T: RawTuple,
{
T::leaf_tuple().vec(width).vec(height).parse(self)
}
prim_methods! {
u8; u16; u32; u64; u128; usize;
i8; i16; i32; i64; i128; isize;
f32; f64;
char; string: String;
}
}
mod token {
use super::multi_token::Leaf;
use std::{any, fmt, marker, str};
pub trait Token: Sized {
type Output;
fn parse(s: &str) -> Self::Output;
fn leaf() -> Leaf<Self> {
Leaf(marker::PhantomData)
}
}
impl<T> Token for T
where
T: str::FromStr,
<Self as str::FromStr>::Err: fmt::Debug,
{
type Output = Self;
fn parse(s: &str) -> Self::Output {
s.parse().unwrap_or_else(|_| {
panic!("Parse error!: ({}: {})", s, any::type_name::<Self>(),)
})
}
}
pub struct Usize1 {}
impl Token for Usize1 {
type Output = usize;
fn parse(s: &str) -> Self::Output {
usize::parse(s)
.checked_sub(1)
.expect("Parse error! (Zero substruction error of Usize1)")
}
}
}
mod multi_token {
use super::{Token, Tokenizer};
use std::{io::BufRead, iter, marker};
pub trait Parser: Sized {
type Output;
fn parse<S: BufRead>(&self, server: &mut Tokenizer<S>) -> Self::Output;
fn vec(self, len: usize) -> VecLen<Self> {
VecLen { len, elem: self }
}
}
pub struct Leaf<T>(pub(super) marker::PhantomData<T>);
impl<T: Token> Parser for Leaf<T> {
type Output = T::Output;
fn parse<S: BufRead>(&self, server: &mut Tokenizer<S>) -> T::Output {
server.parse::<T>()
}
}
pub struct VecLen<T> {
pub len: usize,
pub elem: T,
}
impl<T: Parser> Parser for VecLen<T> {
type Output = Vec<T::Output>;
fn parse<S: BufRead>(&self, server: &mut Tokenizer<S>) -> Self::Output {
iter::repeat_with(|| self.elem.parse(server))
.take(self.len)
.collect()
}
}
pub trait RawTuple {
type LeafTuple: Parser;
fn leaf_tuple() -> Self::LeafTuple;
}
pub trait ParserTuple {
type Tuple: Parser;
fn tuple(self) -> Self::Tuple;
}
pub struct Tuple<T>(pub T);
macro_rules! impl_tuple {
($($t:ident: $T:ident),*) => {
impl<$($T),*> Parser for Tuple<($($T,)*)>
where
$($T: Parser,)*
{
type Output = ($($T::Output,)*);
#[allow(unused_variables)]
fn parse<S: BufRead >(&self, server: &mut Tokenizer<S>) -> Self::Output {
match self {
Tuple(($($t,)*)) => {
($($t.parse(server),)*)
}
}
}
}
impl<$($T: Token),*> RawTuple for ($($T,)*) {
type LeafTuple = Tuple<($(Leaf<$T>,)*)>;
fn leaf_tuple() -> Self::LeafTuple {
Tuple(($($T::leaf(),)*))
}
}
impl<$($T: Parser),*> ParserTuple for ($($T,)*) {
type Tuple = Tuple<($($T,)*)>;
fn tuple(self) -> Self::Tuple {
Tuple(self)
}
}
};
}
impl_tuple!();
impl_tuple!(t1: T1);
impl_tuple!(t1: T1, t2: T2);
impl_tuple!(t1: T1, t2: T2, t3: T3);
impl_tuple!(t1: T1, t2: T2, t3: T3, t4: T4);
impl_tuple!(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5);
impl_tuple!(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6);
impl_tuple!(t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6, t7: T7);
impl_tuple!(
t1: T1,
t2: T2,
t3: T3,
t4: T4,
t5: T5,
t6: T6,
t7: T7,
t8: T8
);
}
trait Scanner: BufRead + Sized {
fn tokenizer(self) -> Tokenizer<Self> {
Tokenizer::new(self)
}
}
impl<R: BufRead> Scanner for R {}
}
pub use self::i::{with_stdin, with_str};
mod prelude {
pub use super::i::{Parser, ParserTuple, RawTuple, Token, Usize1};
}
}
// }}}
ngtkana