#[allow(unused_imports)] use std::{ convert::{Infallible, TryFrom, TryInto as _}, fmt::{self, Debug, Display, Formatter,}, fs::{File}, hash::{Hash, Hasher}, iter::{Product, Sum}, marker::PhantomData, ops::{Add, AddAssign, Sub, SubAssign, Div, DivAssign, Mul, MulAssign, Neg, }, str::FromStr, sync::{atomic::{self, AtomicU32, AtomicU64}, Once}, collections::{*}, mem::{swap}, cmp::{self, Reverse, Ordering, Eq, PartialEq, PartialOrd}, thread::LocalKey, f64::consts::PI, time::Instant, cell::RefCell, io::{self, stdin, Read, read_to_string, BufWriter, BufReader, stdout, Write}, }; #[allow(unused_imports)] use proconio::{input, input_interactive, marker::{*}}; #[allow(unused_imports)] //use rand::{thread_rng, Rng, seq::SliceRandom}; #[allow(unused_imports)] //use ac_library::{*}; #[allow(dead_code)] const INF: i64 = 1<<62; #[allow(dead_code)] const MOD: i64 = 1000000007; #[allow(dead_code)] const D: [(usize, usize); 4] = [(1, 0), (0, 1), (!0, 0), (0, !0)]; #[allow(dead_code)] const D2: [(usize, usize); 8] = [(1, 0), (1, 1), (0, 1), (!0, 1), (!0, 0), (!0, !0), (0, !0), (1, !0)]; use proconio::fastout; #[fastout] fn main() { input!{ n: usize, h: [i32; n], } let mut stack = VecDeque::new(); stack.push_back((1<<30, 1<<30)); let mut ans = 0; for (i, &v) in h.iter().enumerate(){ if i%2==0{ while let Some((l, r)) = stack.pop_front() { if v < l { ans += v; stack.push_front((l, r)); stack.push_front((0, v)); break; } else if v <= r { ans += l; stack.push_front((0, r)); break; } else { ans -= r - l; } } } else { while let Some((l, r)) = stack.pop_front(){ if v < l{ stack.push_front((l, r)); break; } else if v < r{ ans -= v-l; stack.push_front((v, r)); break; } else { ans -= r-l; } } } println!("{}", ans); } }