CodeEff/ECCO huggingface dataset:
# Original solution
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(0,-1),(1,0),(0,1),(-1,0)]
ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)

def main():
    n,m,k = LI()
    d = LI_()
    v = [LI_() for _ in range(n)]
    dd = collections.defaultdict(lambda: None)
    for i in range(m):
        dd[d[i]] = i
    vv = []
    for c in d:
        vv.append([dd[v[c][i]] for i in range(k)])
    vvv = [[vv[i][j] for i in range(m)] for j in range(k)]
    u = set()
    m2 = 2**m
    u.add(m2-1)
    q = [(m2-1, 1)]
    ii = [2**_ for _ in range(m)]
    # print('vv',vv)
    while q:
        qd, qk = q.pop(0)
        # print('q', qd,qk)
        qdi = [di for di in range(m) if qd & ii[di]]
        for vi in range(k):
            t = 0
            vvi = vvv[vi]
            for di in qdi:
                if not vvi[di] is None:
                    t |= ii[vvi[di]]
            # print('vit',vi,t)
            if t in u:
                continue
            if t == 0:
                return qk
            u.add(t)
            q.append((t,qk+1))

    return -1



print(main())




# Optimized solution
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(0,-1),(1,0),(0,1),(-1,0)]
ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)]

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)

def main():
    n,m,k = LI()
    d = LI_()
    v = [LI_() for _ in range(n)]
    dd = collections.defaultdict(lambda: None)
    for i in range(m):
        dd[d[i]] = i
    ii = [2**_ for _ in range(m)]
    vv = [[ii[dd[v[c][i]]] if not dd[v[c][i]] is None else 0  for c in d] for i in range(k)]
    m2 = 2**m
    u = [None] * m2
    u[-1] = 1
    q = [m2-1]
    r = 0
    while q:
        r += 1
        nq = []
        for qd in q:
            qdi = [di for di in range(m) if qd & ii[di]]
            for vi in range(k):
                t = 0
                vvi = vv[vi]
                for di in qdi:
                    t |= vvi[di]
                if not u[t] is None:
                    continue
                if t == 0:
                    return r
                u[t] = 1
                nq.append(t)
        q = nq

    return -1



print(main())
# Original solution
n=int(eval(input()))
a=list(map(int,input().split()))
k=0
b=[]
for i in range(0,n+1):
  k+=a[i]*pow(2,n-i)
  b.append(k)
if k>pow(2,n):
  print((-1))
else:
  current=0
  ans=0
  for i in range(0,n+1):
    current+=a[n-i]
    if i==n:
      ans+=1
    else:
      s=(pow(2,n)-b[n-i-1])//pow(2,i)
      if (s+1)*pow(2,i)<=pow(2,n)-b[n-i-1]:
        s+=1
      current=min(current,s)
      current=min(current,pow(2,n-i))
      ans+=current
  print(ans)

# Optimized solution
n=int(eval(input()))
a=list(map(int,input().split()))
k=0
N=sum(a)
failflag=0
node=1
min1=[]
min2=[]
for i in range(0,n+1):
  node=node*2-a[i]
  if i==0:
    node=1-a[0]
  node=min(node,N)
  min1.append(node+a[i])
  if node<0:
    failflag=1
if failflag==1:
  print((-1))
else:
  current=0
  for i in range(0,n+1):
    current+=a[n-i]
    min2.append(current)
  min2.reverse()
  ans=0
  for i in range(0,n+1):
    ans+=min(min1[i],min2[i])
  print(ans)
# Original solution
import sys
input = sys.stdin.readline
from collections import *

N = int(eval(input()))
A = list(map(int, input().split()))
low = [0]*(N+1)
high = [0]*(N+1)
low[N] = A[N]
high[N] = A[N]

if A[N]>2**N:
    print((-1))
    exit()

for i in range(N-1, -1, -1):
    low[i] = (low[i+1]+1)//2+A[i]
    high[i] = high[i+1]+A[i]
    lim = 2**i
    
    if low[i]>lim:
        print((-1))
        exit()
    
    high[i] = min(high[i], lim)

now = 1
ans = now

#print(low)
#print(high)

for i in range(N):
    now = min(high[i+1], 2*now)
    ans += now
    now -= A[i+1]
    
print(ans)

# Optimized solution
import sys
input = sys.stdin.readline

N = int(eval(input()))
A = list(map(int, input().split()))
low = [0]*(N+1)
high = [0]*(N+1)
low[N] = A[N]
high[N] = A[N]

for i in range(N-1, -1, -1):
    low[i] = (low[i+1]+1)//2+A[i]
    high[i] = high[i+1]+A[i]

if not low[0]<=1<=high[0]:
    print((-1))
    exit()

ans = 1
now = 1

for i in range(N):
    now = min(2*(now-A[i]), high[i+1])
    ans += now

print(ans)
# Original solution
N, *A = list(map(int, open(0).read().split()))

cnt = [0] * (N + 1)
cnt[0] = 1
for i in range(N):
    cnt[i + 1] = (cnt[i] - A[i]) * 2

ans = 0
cur = 0
for i in reversed(list(range(N + 1))):
    cur += A[i]
    ans += min(cnt[i], cur)
        
if all(cnt[i] >= A[i] for i in range(N + 1)):
    print(ans)
else:
    print((-1))


# Optimized solution

N = int(eval(input()))
X = list(map(int, input().split()))

cnt = [0] * (N + 1)
cnt[0] = 1
for i in range(N):
    cnt[i + 1] = (cnt[i] - X[i]) * 2

ans = 0
cur = 0
for i in reversed(list(range(N + 1))):
    cur += X[i]
    ans += min(cnt[i], cur)

if all(cnt[i] >= X[i] for i in range(N + 1)):
    print(ans)
else:
    print((-1))
# Original solution
n=int(eval(input()))
a=list(map(int,input().split()))
tot=sum(a)

v=[1]
for q in a:
    tot-=q
    v.append(min(2*(v[-1]-q),tot))
    
if all([u>=0 for u in v]):
    print((sum(v)))
else:
    print((-1))

# Optimized solution
n,*a=list(map(int,open(0).read().split()))
tot=sum(a)
v=[1]
for q in a:
  tot-=q
  vt=min(2*(v[-1]-q),tot)
  if vt<0:
    print((-1))
    exit()
  v.append(vt)
print((sum(v)))
# Original solution
import sys
input = sys.stdin.readline
n = int(eval(input()))
a = list(map(int, input().split()))

pos = [pow(2, i) - a[i] for i in range(n+1)]
for i in range(n):
    pos[i+1] = pos[i] * 2 - a[i+1]

for i in range(n+1):
    if pos[i] < 0:
        print((-1))
        exit()

cnt = a[-1]
memo = 0
for i in range(n-1, -1, -1):
    cnt += min(pos[i], memo + a[i+1]) + a[i]
    memo = min(pos[i], memo + a[i+1])


print(cnt)

# Optimized solution
import sys
input = sys.stdin.readline
n = int(eval(input()))
a = list(map(int, input().split()))

pos = [0 for i in range(n+1)]
pos[0] = 1 - a[0]
for i in range(n):
    pos[i+1] = pos[i] * 2 - a[i+1]

for i in range(n+1):
    if pos[i] < 0:
        print((-1))
        exit()

cnt = a[-1]
memo = 0
for i in range(n-1, -1, -1):
    cnt += min(pos[i], memo + a[i+1]) + a[i]
    memo = min(pos[i], memo + a[i+1])


print(cnt)
# Original solution
N=int(eval(input()))
A=list(map(int,input().split()))[::-1]

def f(A):
    nodes=[]
    for i in list(range(len(A))):
        t = len(A)-i-1
        if i == 0:
            if 2**t < A[i]:
                return -1
            nodes.append(A[i])
        else:
            tmp = min(nodes[-1] + A[i],2**t)
            anchor = (tmp-A[i])*2
            if anchor < nodes[-1]:
                flag = True
                for j in range(len(nodes))[::-1]:
                    if anchor < nodes[j]:
                        nodes[j] = anchor
                        anchor = (nodes[j]-A[j])*2
                    else:
                        flag = False
                        break
                if flag : return -1        
            nodes.append(tmp)
    return sum(nodes)
  
print((f(A)))

# Optimized solution
N = int(eval(input()))
A = list(map(int, input().split()))

def solve(A):
    ans = 0
    leaves = sum(A)
    prev_node_capacity = 1

    for ai in A:
        if ai > prev_node_capacity:
            return -1
        ans += min(prev_node_capacity, leaves)

        leaves -= ai
        prev_node_capacity -= ai
        prev_node_capacity *= 2

    return ans
  
print((solve(A)))
# Original solution
# coding: utf-8


def solve(*args: str) -> str:
    n = int(args[0])
    A = list(map(int, args[1].split()))

    if 0 < A[0]:
        return '1' if n == 0 and A[0] == 1 else '-1'

    R = [0]*(n+1)
    R[0] = 1
    for i in range(1, n+1):
        R[i] = 2*(R[i-1]-A[i-1])

    prev = 0
    ret = 0
    for i in range(n, -1, -1):
        if R[i] < A[i]:
            ret = -1
            break

        prev = min(R[i], A[i]+prev)
        ret += prev

    return str(ret)


if __name__ == "__main__":
    print((solve(*(open(0).read().splitlines()))))


# Optimized solution
# coding: utf-8


def solve(*args: str) -> str:
    n = int(args[0])
    A = list(map(int, args[1].split()))

    rem = sum(A)
    cur = 1
    ret = 0
    for a in A:
        cur = min(rem, cur)
        rem -= a
        ret += cur
        cur = 2*(cur-a)
        if cur < 0:
            ret = -1
            break

    return str(ret)


if __name__ == "__main__":
    print((solve(*(open(0).read().splitlines()))))
# Original solution
#!/usr/bin/env python3
import sys


def solve(N: int, A: "List[int]"):
    if N==0:
        if A[0] == 1:
            print((1))
        else:
            print((-1)) 
        return 
    
    prev = 0
    leafs = 0
    ans = 0
    for i, a in enumerate(A):
        leafs = leafs*2 + a
        rem = pow(2,i) - leafs
        k = min(rem,sum(A[i+1:]))
        # print(A[i+1:])
        # print(k)
        ans+=k
    # print(leafs)

    rem = pow(2,N) - leafs
    
    if rem<0:
        print((-1))
        return
    print((ans+sum(A)))
    return


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    A = [int(next(tokens)) for _ in range(N - 0 + 1)]  # type: "List[int]"
    solve(N, A)

if __name__ == '__main__':
    main()


# Optimized solution
#!/usr/bin/env python3
import sys


def solve(N: int, A: "List[int]"):
    if N==0:
        if A[0] == 1:
            print((1))
        else:
            print((-1)) 
        return 
    
    s = [0]*(N+1)
    s[N] = A[N]
    for i in range(N-1, -1, -1):
        s[i] = s[i+1] + A[i] 

    leafs = 0
    ans = 0
    for i, a in enumerate(A):
        leafs = leafs*2 + a
        rem = pow(2,i) - leafs
        if i<N:
            # print(sum(A[i+1:]), s[i+1])
            k = min(rem, s[i+1])
            ans+=k
    # print(leafs)

    rem = pow(2,N) - leafs    
    if rem<0:
        print((-1))
        return
    print((ans+sum(A)))
    return


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    A = [int(next(tokens)) for _ in range(N - 0 + 1)]  # type: "List[int]"
    solve(N, A)

if __name__ == '__main__':
    main()
# Original solution
import math
#import numpy as np
import queue
from collections import deque,defaultdict
import heapq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)

def main():
    n = int(ipt())
    a = [int(i) for i in ipt().split()]
    if n == 0 and a[0] == 0:
        print((-1))
        exit()
    elif n == 0 and a[0] == 1:
        print((1))
        exit()
    elif n == 0 and a[0] > 1:
        print((-1))
        exit()
    suma = sum(a)
    ans = a[0]
    can = 1
    for i,ai in enumerate(a):
        if ai > can:
            print((-1))
            exit()
        suma -= ai
        ans += can
        if (can-ai)*2 >= suma:
            can = suma
        else:
            can = (can-ai)*2

    print(ans)




    return

if __name__ == '__main__':
    main()


# Optimized solution
import math
#import numpy as np
import queue
from collections import deque,defaultdict
import heapq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)

def main():
    n = int(ipt())
    a = [int(i) for i in ipt().split()]
    suma = sum(a)
    ans = 0
    can = 1
    for i,ai in enumerate(a):
        if ai > can:
            print((-1))
            exit()
        suma -= ai
        ans += can
        if (can-ai)*2 >= suma:
            can = suma
        else:
            can = (can-ai)*2

    print(ans)




    return

if __name__ == '__main__':
    main()
# Original solution
#!/usr/bin/env python3
 
import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
 
n = I()
a = LI()
if n == 0:
    if a[0] == 1 or a[0] == 0:
        print((1))
        quit()
    else:
        print((-1))
        quit()
for i in range(n):
    if a[i] > 2**i - 1:
        print((-1))
        quit()
if a[-1] > 2**n:
    print((-1))
    quit()

lst = [1]
for i in range(1, n+1):
    l = lst[-1] - a[i-1]
    if l <= 0:
        print((-1))
        quit()
    lst.append(2*l)
if lst[-1] - a[-1] < 0:
    print((-1))
    quit()

i = n-1
tmp = a[-1]
ans = 0
lst2 = [a[-1]]
while i >= 0:
    tmp += a[i]
    tmp = min(tmp, 2**i)
    lst2.append(tmp)
    i -= 1
lst2 = lst2[::-1]
for i in range(n+1):
    ans += min(lst[i], lst2[i])
print(ans)


# Optimized solution
#!/usr/bin/env python3
 
import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
 
n = I()
a = LI()
L = [1]
if a[-1] > 2**n:
    print((-1))
    quit()
if n == 0:
    if a[0] == 0:
        print((-1))
        quit()
L2 = [a[-1]]
for i in range(n)[::-1]:
    L2.append(min(L2[-1] + a[i], 2**i))
L2 = L2[::-1]
ans = 0
for i in range(n+1):
    if i == 0:
        tmp = 1
    else:
        tmp = (L[-1] - a[i-1]) * 2
    if tmp <= 0:
        print((-1))
        quit()
    ans += min(tmp, L2[i])
    L.append(tmp)
if L[-1] - a[-1] < 0:
    print((-1))
    quit()
print(ans)
# Original solution
def main():
    N = int( eval(input()))
    A = list( map( int, input().split()))
    root = 1
    if A[0] == 1:
        if N == 0:
            print((1))
        else:
            print((-1))
        return
    B = A[::-1]
    low = high = B[0]
    # Low = []
    Hight = [high]
    Low = [low]
    for b in B[1:]:
        low = max(1, (low+1)//2) + b
        high = high + b
        Hight.append(high)
        Low.append(low)
    if low > 1:
        print((-1))
        return
    ans = 1
    now = 1
    BHight = Hight[::-1]
    BLow = Low[::-1]
    for i in range(1,N+1):
        high = BHight[i]
        low = BLow[i]
        if high < now or now*2 < low:
            print((-1))
            return
        leaf = A[i]
        now = min(high, now*2)
        ans += now
        now -= leaf
    print(ans)
if __name__ == '__main__':
    main()

# Optimized solution
#import sys
#input = sys.stdin.readline
def main():
    N = int( eval(input()))
    A = list( map( int, input().split()))
    root = 1
    if A[0] == 1:
        if N == 0:
            print((1))
        else:
            print((-1))
        return
    B = A[::-1]
    low = high = B[0]
    # Low = []
    Hight = [high]
    
    for b in B[1:]:
        low = max(1, (low+1)//2) + b
        high = high + b
        Hight.append(high)
    if low > 1:
        print((-1))
        return
    ans = 1
    now = 1
    BHight = Hight[::-1]
    for i in range(1,N+1):
        h = BHight[i]
        leaf = A[i]
        # print("h",h)
        now = min(h, now*2)
        ans += now
        now -= leaf
        # print(now)
    print(ans)
if __name__ == '__main__':
    main()
# Original solution
n = int(eval(input()))
A = list(map(int, input().split()))
if n==0:
    print((1 if A[0] == 1 else -1))
    exit()
if A[0]!=0:
    print((-1))
    exit()
node1=[0]*(n+1)
node1[0]=1
node2=[0]*(n+1)
node2[0]=1
node2[-1]=A[-1]
for i in range(n):
    x=(node1[i]-A[i])*2
    node1[i+1]=x

for i in range(n,0,-1):
    x=(node2[i]+A[i-1])
    node2[i-1]=x

ans=[]

for i in range(n+1):
    x=min(node1[i],node2[i])
    if x<A[i]:
        print((-1))
        exit()
    ans.append(x)
print((sum(ans)))

# Optimized solution
n = int(eval(input()))
A = list(map(int, input().split()))
if n==0:
    print((1 if A[0] == 1 else -1))
    exit()
if A[0]>0:
    print((-1))
    exit()
if A[-1]>2**n:
    print((-1))
    exit()
node1=[0]*(n+1)
node1[0]=1
node2=[0]*(n+1)
node2[-1]=A[-1]
for i in range(n):
    x=(node1[i]-A[i])*2
    if x<1:
        print((-1))
        exit()
    node1[i+1]=x
#print(node1)
for i in range(n-1,-1,-1):
    x=(node2[i+1]+A[i])
    node2[i]=x
ans=[]

for i in range(n+1):
    x=min(node1[i],node2[i])
    if x<A[i]:
        print((-1))
        exit()
    ans.append(x)
print((sum(ans)))
# Original solution
from math import ceil

def a():
    N = int(eval(input()))
    A = list(map(int,input().split()))
    INF = 10**13
    if N == 0:
        if A[0] == 1:
            return 1
        else:
            return -1

    BMAX = [INF] * (N+1)
    BMIN = [1] * (N+1)

    a = 1
    for i in range(N+1):
        BMAX[i] = min(BMAX[i] , a - A[i])
        a = BMAX[i] * 2
    BMAX[N] = 0
    BMIN[0] = 1
    BMIN[N] = 0

    for i in range(N-1,-1,-1):
        BMAX[i] = min(BMAX[i],BMAX[i+1]+A[i+1])
        BMIN[i] = max(BMIN[i],ceil((BMIN[i+1]+A[i+1])/2))

    for i in range(1,N+1):
        BMAX[i] = min(BMAX[i],BMAX[i-1]*2-A[i])
        BMIN[i] = max(BMIN[i],BMIN[i-1]-A[i])

    ans = 0
    for i in range(0,N+1):
        if BMIN[i] > BMAX[i]:
            return -1
        ans += (BMAX[i] + A[i])
    return ans

print((a()))

# Optimized solution
from math import ceil

def a():
    N = int(eval(input()))
    A = list(map(int,input().split()))
    INF = 10**13
    if N == 0:
        if A[0] == 1:
            return 1
        else:
            return -1

    BMAX = [INF] * (N+1)
    BMIN = [1] * (N+1)

    BMAX[0] = 1 - A[0]
    BMAX[N] = 0
    BMIN[0] = 1
    BMIN[N] = 0

    for i in range(N-1,-1,-1):
        BMAX[i] = min(BMAX[i],BMAX[i+1]+A[i+1])
        BMIN[i] = max(BMIN[i],ceil((BMIN[i+1]+A[i+1])/2))

    if BMIN[0] > BMAX[0]:
        return -1

    for i in range(1,N+1):
        BMAX[i] = min(BMAX[i],BMAX[i-1]*2-A[i])
        BMIN[i] = max(BMIN[i],BMIN[i-1]-A[i])
        if BMIN[i] > BMAX[i]:
            return -1
        
    return sum(BMAX)+sum(A)

print((a()))
# Original solution
from collections import defaultdict as dd
import bisect
from sys import exit
n = int(eval(input()))
A = list(map(int, input().split()))

coutner = 0
dp = dd(int)
dp[1] = 1
limit = [0] * (n + 1)
total = 0
for i in range(n, -1, -1):
    total += A[i]
    limit[i] = total
#print(limit)

for depth in range(n):
    mov_dic = dd(lambda: 0)
    for now_num, total in list(dp.items()):
        if now_num - A[depth] > 0:
            mov_dic[now_num - A[depth]] = total
    #print("mov_dic", mov_dic)

    dp = dd(int)
    mov_dic_keys = set(mov_dic.keys())
    for now_num, total in list(mov_dic.items()):
        mov_dic_keys.remove(now_num)
        for next_num in range(now_num, min(now_num*2 + 1, limit[depth] + 1)):
            if now_num in mov_dic_keys:
                break
            dp[next_num] = max(total + next_num, dp[next_num])
    #print(limit[depth], "dp", dp)

if dp[A[-1]] == 0:
    print((-1))
else:
    print((dp[A[-1]]))

# Optimized solution
from collections import defaultdict as dd
import bisect
from sys import exit
n = int(eval(input()))
A = list(map(int, input().split()))

coutner = 0
dp = dd(int)
dp[1] = 1
limit = [0] * (n + 1)
total = 0
for i in range(n, -1, -1):
    total += A[i]
    limit[i] = total
#print(limit)

"""
for depth in range(n):
    mov_dic = dd(lambda: 0)
    for now_num, total in dp.items():
        if now_num - A[depth] > 0:
            mov_dic[now_num - A[depth]] = total
    #print("mov_dic", mov_dic)

    dp = dd(int)
    mov_dic_keys = set(mov_dic.keys())
    for now_num, total in mov_dic.items():
        mov_dic_keys.remove(now_num)
        for next_num in range(now_num, min(now_num*2 + 1, limit[depth] + 1)):
            if now_num in mov_dic_keys:
                break
            dp[next_num] = max(total + next_num, dp[next_num])
    #print(limit[depth], "dp", dp)

if dp[A[-1]] == 0:
    print(-1)
else:
    print(dp[A[-1]])
"""

if n == 0:
    if A[0] == 1:
        print((1))
    else:
        print((-1))
    exit()

now_num = 1
now_total = 1
for depth in range(n):
    mov_num = now_num - A[depth]
    #print(mov_num)

    if mov_num > 0:
        now_num = min(mov_num * 2, limit[depth+1])
        now_total += now_num
    else:
        print((-1))
        exit()
if now_num == A[n]:
    print(now_total)
else:
    print((-1))
# Original solution
N = int(eval(input()))
*A, = list(map(int, input().split()))

Asum = [a for a in A]
for i in range(N-1, -1, -1):
    Asum[i] += Asum[i+1]

ans = 0
v = 1  # 子になれる頂点数
for i in range(N+1):
    if v < A[i]:
        ans = -1
        break

    ans += v
    p = v-A[i]
    if i < N:
        if p > Asum[i+1]:
            ans = -1
            break
        v = min(Asum[i+1], 2*p)

print(ans)


# Optimized solution
N = int(eval(input()))
*A, = list(map(int, input().split()))

Asum = [a for a in A]
for i in range(N-1, -1, -1):
    Asum[i] += Asum[i+1]

ans = 0
v = 1  # 子になれる頂点数
for i in range(N+1):
    if v < A[i]:
        ans = -1
        break

    ans += v
    p = v-A[i]
    if i < N:
        v = min(Asum[i+1], 2*p)

print(ans)
# Original solution
def main():
  eval(input())
  A = list(map(int, input().split()))
  cusum = [0] * len(A)
  cusum[-1] = A[-1]

  if A[0] > 1:
    print((-1))
    return

  for i in range(len(A)-2, -1, -1):
    cusum[i] = cusum[i+1] + A[i]

  pre_node = 1
  ans = 1
  for i in range(1, len(A)):
    node = (pre_node - A[i-1]) * 2

    if node < A[i]:
        print((-1))
        return

    pre_node = min(node, cusum[i])
    ans += pre_node

  print(ans)

if __name__ == '__main__':
  main()
    


# Optimized solution
def main():
  eval(input())
  in_a = list(map(int, input().split()))
  leaves = [0] * len(in_a)
  leaves[-1] = in_a[-1]

  if in_a[0] > 1:
    print((-1))
    return

  for i in range(len(in_a)-2, -1, -1):
    leaves[i] = leaves[i+1] + in_a[i]

  node = 1
  total = 1
  
  for i in range(1, len(in_a)):
    n = (node - in_a[i-1]) * 2

    if n < in_a[i]:
        print((-1))
        return

    node = min(n, leaves[i])
    total += node

  print(total)

if __name__ == '__main__':
  main()