// ---------- begin input macro ---------- // reference: https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 macro_rules! input { (source = $s:expr, $($r:tt)*) => { let mut iter = $s.split_whitespace(); input_inner!{iter, $($r)*} }; ($($r:tt)*) => { let s = { use std::io::Read; let mut s = String::new(); std::io::stdin().read_to_string(&mut s).unwrap(); s }; let mut iter = s.split_whitespace(); input_inner!{iter, $($r)*} }; } macro_rules! input_inner { ($iter:expr) => {}; ($iter:expr, ) => {}; ($iter:expr, $var:ident : $t:tt $($r:tt)*) => { let $var = read_value!($iter, $t); input_inner!{$iter $($r)*} }; } macro_rules! read_value { ($iter:expr, ( $($t:tt),* )) => { ( $(read_value!($iter, $t)),* ) }; ($iter:expr, [ $t:tt ; $len:expr ]) => { (0..$len).map(|_| read_value!($iter, $t)).collect::>() }; ($iter:expr, chars) => { read_value!($iter, String).chars().collect::>() }; ($iter:expr, bytes) => { read_value!($iter, String).bytes().collect::>() }; ($iter:expr, usize1) => { read_value!($iter, usize) - 1 }; ($iter:expr, $t:ty) => { $iter.next().unwrap().parse::<$t>().expect("Parse error") }; } // ---------- end input macro ---------- use std::io::Write; use std::collections::*; type Map = BTreeMap; type Set = BTreeSet; type Deque = VecDeque; fn run() { input! { n: usize, a: [i32; n], } let pos = |x: i32| -> usize { assert!(x > 0); (x as u32).next_power_of_two().trailing_zeros() as usize }; let w = 20; let mut value_pos = vec![Set::new(); w]; let mut pos_value = vec![Set::new(); w]; let mut dp = vec![0; w]; for (i, &a) in a.iter().enumerate() { if a > 0 { let p = pos(a); value_pos[p].insert((a, i)); pos_value[p].insert((i, a)); } } let mut ans = 0; loop { let mut index = n; let mut v = 0; for (i, set) in pos_value.iter().enumerate() { if let Some(&(k, a)) = set.iter().next() { if k < index { index = k; v = a + dp[i]; } } } if index == n { break; } ans += 1; let sub = v ; let x = pos(sub); let del = value_pos[x].range((sub - dp[x], 0)..).cloned().collect::>(); for (v, p) in del { value_pos[x].remove(&(v, p)); pos_value[x].remove(&(p, v)); let v = v + dp[x] - sub; if v > 0 { let x = pos(v); value_pos[x].insert((v - dp[x], p)); pos_value[x].insert((p, v - dp[x])); } } for i in (x + 1)..w { while let Some(&(v, p)) = value_pos[i].iter().next() { if pos(v + dp[i]) == i { break; } value_pos[i].remove(&(v, p)); pos_value[i].remove(&(p, v)); let v = v + dp[i] - sub; if v > 0 { let x = pos(v); value_pos[x].insert((v - dp[x], p)); pos_value[x].insert((p, v - dp[x])); } } dp[i] -= sub; } } println!("{}", ans); } fn main() { run(); }