N = gets.to_i B = gets.split(" ").map{|s| s.to_i} from = [] to = [] cnt = 0 B.each_with_index {|n, i| if n == 0 then if from.length > 0 f = from.shift cnt += i - f else to << i end else while n > 1 and to.length > 0 do t = to.shift cnt += i - t n -= 1 end if n > 1 then from.concat([i] * (n-1)) end end } puts cnt