Created
February 18, 2021 17:27
-
-
Save ashiato45/b685f6528fb07f5c014a22f92fd92ece to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mod acc_util{ | |
pub struct Accum{ | |
acc: Vec<i64> | |
} | |
impl Accum{ | |
pub fn new(a: &Vec<i64>) -> Accum{ | |
let mut acc: Vec<i64> = vec![]; | |
let mut s = 0; | |
for i in a{ | |
s += *i; | |
acc.push(s); | |
} | |
Accum{acc} | |
} | |
pub fn get(&self, l: usize, r: usize) -> i64{ | |
let mut l = l; | |
let mut r = r; | |
r = r.min(self.acc.len()); | |
l = l.max(0); | |
if r <= l{ | |
return 0; | |
} | |
return self.acc[r - 1] - (if l == 0 {0} else {self.acc[l - 1]}); | |
} | |
} | |
#[test] | |
fn test(){ | |
let x = vec![1, 10, 100, 1000]; | |
let a = Accum::new(&x); | |
assert_eq!(a.get(0, 4), 1111); | |
assert_eq!(a.get(1, 2), 10); | |
assert_eq!(a.get(1, 3), 110); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment