competitive_library/algorithm/
convex_hull_trick.rs1use std::collections::VecDeque;
7
8pub struct LinearFunction(i64, i64);
9
10pub struct ConvexHullTrick {
11 d: VecDeque<LinearFunction>,
12 f: fn(&LinearFunction, i64) -> i64,
13}
14fn f(f: &LinearFunction, x: i64) -> i64 {
15 f.0 * x + f.1
16}
17
18impl ConvexHullTrick {
19 pub fn new() -> Self {
20 ConvexHullTrick {
21 d: VecDeque::new(),
22 f,
23 }
24 }
25 pub fn from(f: fn(&LinearFunction, i64) -> i64) -> Self {
26 ConvexHullTrick {
27 d: VecDeque::new(),
28 f,
29 }
30 }
31 fn check(f1: &LinearFunction, f2: &LinearFunction, f3: &LinearFunction) -> bool {
32 (f2.0 - f1.0) * (f3.1 - f2.1) >= (f2.1 - f1.1) * (f3.0 - f2.0)
33 }
34
35 pub fn add_line(&mut self, a: i64, b: i64) {
38 let f = LinearFunction(a, b);
39
40 while self.d.len() >= 2
41 && ConvexHullTrick::check(&self.d[self.d.len() - 2], &self.d[self.d.len() - 1], &f)
42 {
43 self.d.pop_back();
44 }
45 self.d.push_back(f);
46 }
47
48 pub fn query(&mut self, x: i64) -> i64 {
50 while self.d.len() >= 2 && (self.f)(&(self.d)[0], x) >= (self.f)(&(self.d)[1], x) {
51 self.d.pop_front();
52 }
53 (self.f)(&(self.d)[0], x)
54 }
55}
56impl Default for ConvexHullTrick {
57 fn default() -> Self {
58 ConvexHullTrick::new()
59 }
60}
61
62#[cfg(test)]
63mod tests {
64 use super::*;
65 #[test]
66 fn test_cht() {
67 let mut cht = ConvexHullTrick::new();
68 for (a, b) in &[(2, 0), (1, 1), (0, -1), (-1, 0)] {
69 cht.add_line(*a, *b);
70 }
71 let ans: Vec<_> = (0..10).map(|i| cht.query(-5 + i)).collect();
72 assert_eq!(ans, [-10, -8, -6, -4, -2, -1, -1, -2, -3, -4]);
73 }
74}