n = int(input()) a = list(map(int, input().split())) L = 0 while a[L] == 0 and L < n: L += 1 if L == n: print(0) else: R = L while L < n - 1: count = 0 while R < n - 1 and a[R] != a[R + 1]: R += 1 count += 1 if R == n - 1 and count > 1: count -= 1 a[L] += count while L < R - 1: L += 1 count -= 1 if a[L] == 1: a[L] += count if L == R: L += 1 R = L elif a[R] == 0: while R < n - 1 and a[R] == 0: R += 1 L = R elif a[R] == 1: L = R a[n - 1] = 0 ans = 0 for i in a: ans += i print(ans)