use std::io::Read; use std::collections::VecDeque; fn main() { let mut all_data = String::new(); std::io::stdin().read_to_string(&mut all_data).ok(); let all_data: Vec<&str> = all_data.trim().split('\n').map(|s| s.trim()).collect(); let n: usize = all_data.iter().next().unwrap().parse::().unwrap(); let b: Vec = all_data.iter().skip(1).next().unwrap().split_whitespace().map(|s| s.parse::().unwrap()).collect(); let mut empty_indices = VecDeque::new(); let mut overed_indices = VecDeque::new(); let mut cost: usize = 0; b.iter().enumerate().for_each(|pair| { let index = pair.0; let count = pair.1; if count == &0 { if overed_indices.is_empty() { empty_indices.push_back(index); } else { cost += index - overed_indices.pop_back().unwrap(); } } else if count > &1 { if empty_indices.is_empty() { (0..(count - 1)).for_each(|_| { overed_indices.push_back(index); }); } else { let mut iter_count = count - 1; while !empty_indices.is_empty() && iter_count > 0 { cost += index - empty_indices.pop_front().unwrap(); iter_count -= 1; } for _ in 0..iter_count { overed_indices.push_back(index); } } } }); println!("{}", cost); }