Problem:
 Score : 600 points    Problem Statement Given is an integer sequence of length N+1 : A_0, A_1, A_2, \ldots, A_N . Is there a binary tree of depth N such that, for each d = 0, 1, \ldots, N , there are exactly A_d leaves at depth d ? If such a tree exists, print the maximum possible number of vertices in such a tree; otherwise, print -1 .      Notes  A binary tree is a rooted tree such that each vertex has at most two direct children.  A leaf in a binary tree is a vertex with zero children.  The depth of a vertex v in a binary tree is the distance from the tree's root to v . (The root has the depth of 0 .)  The depth of a binary tree is the maximum depth of a vertex in the tree.       Constraints  0 \leq N \leq 10^5  0 \leq A_i \leq 10^{8} ( 0 \leq i \leq N )  A_N \geq 1  All values in input are integers.         Input Input is given from Standard Input in the following format:  N  A_0  A_1  A_2  \cdots  A_N       Output Print the answer as an integer.        Sample Input 1 3
0 1 1 2      Sample Output 1 7  Below is the tree with the maximum possible number of vertices. It has seven vertices, so we should print 7 .         Sample Input 2 4
0 0 1 0 2      Sample Output 2 10       Sample Input 3 2
0 3 1      Sample Output 3 -1       Sample Input 4 1
1 1      Sample Output 4 -1       Sample Input 5 10
0 0 1 1 2 3 5 8 13 21 34      Sample Output 5 264

Solution (Python):




N = int(input())
A = list(map(int,input().split()))

li1 = [1]
for i in range(N):
    
    
    
    li1.append(min(10**15,2*li1[-1]-A[i]*2))

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

ans = 0
li3 = []
for i in range(N+1):
    ans += min(li1[i],li2[i])
    li3.append(ans) 
    if li1[i]<A[i]:
        print(-1)
        break
else:
    print(ans)

Solution (Python):
from itertools import accumulate
N = int(input())
As = list(map(int, input().split()))

accR = reversed(list(accumulate(reversed(As))))
num = 1
MAX = 10 ** 13
ans = 0
for a, limit in zip(As, accR):
    tmp = min(num, limit)
    if a > tmp:
        print(-1)
        exit()
    ans += tmp
    num = (tmp - a) * 2
    if num >= MAX:
        num = MAX
print(ans)

Solution (Python):
import sys

sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]

def main():
    n=II()
    aa=LI()
    
    if n==0 and aa[0]!=1:
        print(-1)
        exit()

    if n>0 and aa[0]>0:
        print(-1)
        exit()

    node=[0]*(n+1)
    node[0]=1
    node[n]=aa[n]

    for i in range(n-1,0,-1):
        a=aa[i]
        if a>(1<<i):
            print(-1)
            exit()

        node[i]=min(1<<i,node[i+1]+aa[i],((1<<(i-1))-aa[i-1])*2)

    

    for i in range(1,n+1):
        node[i]=min((node[i-1]-aa[i-1])*2,node[i])

    if node[n]!=aa[n]:
        print(-1)
        exit()
    
    print(sum(node))


main()

Solution (Python):
def task(n, a):
    mxs = []
    current = 1

    for i in range(0, n + 1):
        mxs.append(current)
        current = (current - a[i]) * 2

        if current < 0:
            print(-1)
            return

    

    v = 0
    nodes = 0
    for i in reversed(range(0, n + 1)):
        nodes = min(nodes + a[i], mxs[i])
        v += nodes

    print(v)


n = int(input())
a = list(map(int, input().split()))
task(n, a)

Solution (Python):
import sys

n=int(input())
A=list(map(int,input().split()))
now=1
s=sum(A)
ans=1
if n==0:
    if A[0]!=1:
        print(-1)
    else:
        print(1)
    sys.exit()
if A[0]!=0:
    print(-1)
    sys.exit()
for i in range(1,n+1):  
    if A[i]>2*now:
        print(-1)
        sys.exit()
    if s>=2*now:
        ans+=2*now
        now=2*now-A[i]
        
    else:
        ans+=s
        now=s-A[i]
    s-=A[i]
print(ans)

Solution (Python):
from math import gcd

from math import factorial as f

from math import ceil,floor,sqrt
import math

import bisect
import re
import heapq


from copy import deepcopy
import itertools
from itertools import permutations

from sys import exit

ii = lambda : int(input())
mi = lambda : map(int,input().split())
li = lambda : list(map(int,input().split()))


yes = "Yes"
no = "No"


def main():
    n = ii()
    a = li()
    if n!=0 and a[0]!=0:
        print(-1)
        exit()
    if n == 0 and a[0]!=1:
        print(-1)
        exit()
    M = 1
    m = 1
    flag = True
    mlist = []
    for i in range(n+1):
        mlist.append(M)
        if a[i]>M:
            flag = False
            break
        M-=a[i]
        M*=2
    if not flag:
        print(-1)
        exit()
    mlist.append(0)

    ans = 0
    tmp = 0
    

    for _ in range(n+1):
        i = n-_
        
        tmp = min(tmp,mlist[i+1])
        ans+=tmp
        tmp +=a[i]
        
    print(ans+1)




main()

Solution (Python):
N = int(input())

A = list(map(int,input().split()))

c = 1
M = [] 
INF = 10**16
for a in A:
    c -= a
    M.append(c)
    c *= 2

    c = min(INF, c)
    
if c < 0:
    print(-1)
else:
    cnt = A[-1]
    num = A[-1]
    for a,m in zip(reversed(A[:-1]),reversed(M[:-1])):
        n = min(num, m)
        cnt += n+a
        num = n+a
    print(cnt)

Solution (Python):
import sys
input = sys.stdin.buffer.readline

N = int(input())
A = list(map(int, (input().split())))
tmp = sum(A)
root = 0
ans = 0
for i in range(N+1):
    if i==0:
        mx = 1
    else:
        mx = root*2
    if A[i] > mx:
        ans = -1
        break
    root = min(tmp, mx) - A[i]
    tmp -= A[i]
    ans += root + A[i]

print(ans)

Solution (Python):
from sys import exit
def log2(x):
    ans = 0
    while(x):
        x //= 2
        ans += 1
    return ans

n = int(input())
n += 1
a = list(map(int, input().split()))
cnt = 1
ans = 0
s = [0 for i in range(n)]
s[-1] = a[-1]
for i in range(n - 2, -1, -1):
    s[i] = s[i + 1] + a[i]
for i in range(n):
    cnt = cnt * 2 - a[i] * 2
    if (i + 1 < n):
        ans += min(cnt, s[i + 1])
if (cnt < 0):
    print(-1)
    exit(0)
print(ans + 1)

Solution (Python):
N = int(input())
A = list(map(int, input().split()))
B = []
now = 1
ans = 1

if A[0] == 2:
    print(-1)
    exit()
if A[0] == 1 and len(A) != 1:
    print(-1)
    exit()

for a in A[1:]:
    now *= 2
    now -= a
    ans += a
    if now < 0:
        print(-1)
        exit()
    B.append(now)

cnt = A[-1]
for a, b in zip(A[:-1][::-1], B[:-1][::-1]):
    if cnt <= b:
        ans += cnt
    else:
        cnt = b
        ans += cnt
    cnt += a
print(ans)

Solution (Python):











import sys
sys.setrecursionlimit(10**6)
input=sys.stdin.readline
from math import floor,sqrt,factorial,hypot,log 
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict,deque
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
from copy import deepcopy
from fractions import gcd
from random import randint
def ceil(a,b): return (a+b-1)//b
inf=float('inf')
mod = 10**9+7
def pprint(*A): 
    for a in A:     print(*a,sep='\n')
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def div_cnt(n):
    res = 0
    while(n):
        n/=2
        res += 1
    return res
def ok(D):
    for i,d in enumerate(D):
        if(div_cnt(d) > i+1):
            return False
    return True
def main():
    N=I()
    D=LI()
    D_rev = D[::-1]
    up = 10**18
    B = [1]*(N+1) 
    for i in range(N):
        B[i + 1] = min(up, (B[i]-D[i]) * 2) 
    
    B_rev = B[::-1]

    ans = 0
    now = 0
    for i,a in enumerate(D_rev):
        if(a>B_rev[i]):
            print(-1)
            return 
        now += a
        now = min(now, B_rev[i])
        ans += now
    print(ans)
if __name__ == '__main__':
    main()

Solution (Python):
n = int(input())
leaves = list(map(int, input().split()))
rest_leaves = [0 for i in range(n+2)]
for i in range(n, -1, -1):
	rest_leaves[i] = rest_leaves[i+1] + leaves[i]



def solve():
	nodes = 0
	current_active = 1
	for i in range(n+1):
		
		current_active -= leaves[i]
		if current_active < 0:
			print(-1)
			return
		current_active = min(rest_leaves[i+1], current_active)
		if i == n:
			current_active = 0
		
		nodes += current_active + leaves[i]
		current_active *= 2
	print(nodes)
	return


solve()

Solution (Python):

from collections import defaultdict, deque
from heapq import heappush, heappop
from itertools import permutations, accumulate
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline().split()]
def S():
    res = list(sys.stdin.readline())
    if res[-1] == "\n":
        return res[:-1]
    return res
def IR(n):
    return [I() for i in range(n)]
def LIR(n):
    return [LI() for i in range(n)]
def SR(n):
    return [S() for i in range(n)]
def LSR(n):
    return [LS() for i in range(n)]

sys.setrecursionlimit(1000000)
mod = 1000000007

def solve():
    n = I()
    a = LI()
    if n == 0:
        if a[0] == 1:
            print(1)
        else:
            print(-1)
        return
    if a[0] == 1:
        print(-1)
        return
    k = 1-a[0]
    M = [1]
    p = 1
    for i in range(n):
        if k <= 0:
            print(-1)
            return
        M.append(min(p,k) << 1)
        k = M[i+1] - a[i+1]
        p <<= 1
    if k < 0:
        print(-1)
        return
    s = a[-1]
    ans = s
    for i in range(n)[::-1]:
        s = min(M[i],s+a[i])
        ans += s
    print(ans)
    return


if __name__ == "__main__":
    solve()

Solution (Python):
n = int(input())
a = [int(an) for an in input().split()]

remaining_leafs = sum(a)

layer_count = 1
vertex_count = 0
for i in range(len(a)):
    vertex_count += layer_count
    layer_count -= a[i]
    remaining_leafs -= a[i]
    if layer_count < 0:
        vertex_count = -1
        break
    layer_count = min(layer_count*2, remaining_leafs)

print(vertex_count)

Solution (Python):

import sys
input = sys.stdin.readline

n = int(input())
a = [int(item) for item in input().split()]
max_node = []
current = 1
for i, item in enumerate(a):
    max_node.append(current)
    current = (current - item) * 2

a.reverse()
max_node.reverse()

prev = 0
ans = 0
for i, (item, mx_nd) in enumerate(zip(a, max_node)):
    lower_bound = item + (prev + 1) // 2
    upper_bound = item + prev
    if lower_bound > mx_nd:
        print(-1)
        exit()
    prev = min(upper_bound, mx_nd)
    ans += prev
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline


def read():
    N = int(input().strip())
    A = list(map(int, input().strip().split()))
    return N, A


def solve(N, A):
    max_leaves = sum(A)
    if N == 0 and A[0] == 1:
        return 1
    if A[0] > 0:
        return -1
    ans = 1
    n_nodes = 1
    for i in range(1, N+1):
        n_nodes = min(n_nodes * 2, max_leaves)
        ans += n_nodes
        if i < N and A[i] > n_nodes - 1:
            return -1
        max_leaves -= A[i]
        n_nodes -= A[i]
    if n_nodes != 0:
        return -1
    return ans


if __name__ == '__main__':
    inputs = read()
    outputs = solve(*inputs)
    if outputs is not None:
        print("%s" % str(outputs))

Solution (Python):
def solve(n, a_list):

    
    b_list = [0] * (n + 1)  

    for d in range(n + 1):
        if d == 0:
            n_nodes = 1
        else:
            n_nodes = b_list[d - 1] * 2
        if a_list[d] > n_nodes:
            return -1
        b_list[d] = n_nodes - a_list[d]
    
    
    b_list[n] = 0
    for i in range(n - 1, -1, -1):
        b_list[i] = min(b_list[i], a_list[i + 1] + b_list[i + 1])
    res = sum(a_list) + sum(b_list)
    
    return res


def main():
    n = int(input())
    a_list = list(map(int, input().split()))
    res = solve(n, a_list)
    print(res)


def test():
    assert solve(3, [0, 1, 1, 2]) == 7
    assert solve(4, [0, 0, 1, 0, 2]) == 10
    assert solve(2, [0, 3, 1]) == -1
    assert solve(10, [0, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34]) == 264


if __name__ == "__main__":
    test()
    main()

Solution (Python):
n=int(input())
a=list(map(int,input().split()))
if n==0:
  if a[0]==1:print(1)
  else:print(-1)
  exit()
if a[0]:
  exit(print(-1))
b=[1]
for i in range(1,n+1):
  b.append(b[-1]*2-a[i])
b[-1]=a[-1]
for i in range(n,0,-1):
  b[i-1]=min(b[i-1],b[i])
  if not(b[i-1]<=b[i]<=2*b[i-1]):exit(print(-1))
  b[i-1]+=a[i-1]
print(sum(b))

Solution (Python):
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")

n = int(input())
a = list(map(int, input().split()))
nmax = [None]*(n+1)
nmax[-1] = 0
for i in range(n-1, -1, -1):
    nmax[i] = nmax[i+1] + a[i+1]
    
k = 1
ans = 0
for i,(num, M) in enumerate(zip(a, nmax)):
    if k<num:
        ans = -1
        break
    k -= num
    k = min(M, k)
    ans += (k+num)
    k *= 2
print(ans)

Solution (Python):
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [LI() for _ in range(row)]
        return map(list, zip(*read_all))



def ceil(a,b):
    return a//b + int(a%b != 0)

N = I()
A = LI()

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

mad = [0]*(N+1)
mid = [0]*(N+1)
mad[-1] = A[-1]
mid[-1] = A[-1]
for i in range(N)[::-1]:
    mad[i] = mad[i+1]+A[i]
    mid[i] = ceil(mid[i+1],2)+A[i]


ans = 0
for i in range(N+1):
    if mad[i] < 0 or mau[i] < 0:
        print('-1')
        exit()
    if mid[i] > mau[i]:
        print('-1')
        exit()
    if miu[i] > mad[i]:
        print('-1')
        exit()
    ans += min(mad[i],mau[i])

print(ans)

Solution (Python):
N = int(input())
A = list(map(int, input().split()))
flag = True
if A[0] != 0:
    flag = False

ans = 0
cur = 1

nodes = [0] * (N + 1)
nodes[0] = 1
for i in range(1, N + 1):
    cur *= 2
    nodes[i] = cur
    cur -= A[i]
    if cur < 0:
        flag = False

L = 0
for i in range(N, -1, -1):
    L += A[i]
    L = min(L, nodes[i])
    ans += L

if N == 0:
    if A[0] == 1:
        print(1)
    else:
        print(-1)
elif flag:
    print(ans)
else:
    print(-1)

Solution (Python):
LI = lambda: list(map(int, input().split()))
n = int(input())
a = LI()

maxnodes = [1]
sumnodes = 0

if n == 0:
    if a[0] == 1:
        print(1)
    else:
        print(-1)
else:
    for d in range(1, n+1):
        tmp = (maxnodes[-1]-a[d-1])*2
        if tmp < 0:
            print(-1)
            break
        else:
            maxnodes.append(tmp)
    else:
        if maxnodes[d] < a[d]:
            print(-1)
        else:
            maxnodes[d] = a[d]
            sumnodes += a[d]
            for d in range(n-1, -1, -1):
                maxnodes[d] = min(maxnodes[d+1]+a[d], maxnodes[d])
                sumnodes += maxnodes[d]
            print(sumnodes)

Solution (Python):
def examA():
    H1, M1, H2, M2, K = LI()
    T = (H2-H1)*60 + (M2-M1)
    ans = T-K
    print(ans)
    return

def examB():
    T = SI()
    ans = ""
    for t in T:
        if t=="?":
            ans += "D"
        else:
            ans += t
    print(ans)
    return

def examC():
    N = I()
    A = LI()
    check = 1<<N
    for i,a in enumerate(A):
        check -= (1<<(N-i))*a
    if check<0:
        print(-1)
        return
    ans = 0
    cnt = 1
    less = sum(A)
    for i in range(N+1):
        a = A[i]
        if cnt>less:
            cnt = less
        ans += cnt
        less -= a
        cnt = (cnt-a)*2
    print(ans)
    return

def examD():
    ans = 0
    print(ans)
    return

def examE():
    ans = 0
    print(ans)
    return

def examF():
    ans = 0
    print(ans)
    return

import sys,bisect,itertools,heapq,math,random
from copy import deepcopy
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
def I(): return int(input())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]

sys.setrecursionlimit(10**7)

if __name__ == '__main__':
    examC()

"""
142
12 9 1445 0 1
asd dfg hj o o
aidn
"""

Solution (Python):
n = int(input())
a = list(map(int, input().split()))
b = a[::-1]

if n == 0 and a[0] == 1:
    print(1)
    exit()

if n == 0:
    print(-1)
    exit()
      
if a[0] >= 1:
    print(-1)
    exit()
    
ans = [0] * (n + 1)
for i in range(n):
    ans[i + 1] = ans[i] + b[i]

ans = ans[::-1]

ans = ans[1::]
a = a[1::]

res = 1
prev_cnt = 1

for i in range(n):
    cnt = min(prev_cnt * 2, ans[i] + a[i])
    if cnt < a[i]:
        print(-1)
        exit()
    res += cnt
    prev_cnt = cnt - a[i]
print(res)

Solution (Python):
import sys
N = int(input())

A = list(map(int,input().split()))

ans = 0
v = 1

maxv = []

for i in range(N+1):

    if v <= 0:
        print (-1)
        sys.exit()
    
    maxv.append(v)

    v -= A[i]
    v *= 2

if v < 0:
    print (-1)
    sys.exit()



now = 0
for i in range(N,-1,-1):

    now = min(now + A[i] , maxv[i])
    
    ans += now

print (ans)

Solution (Python):
import sys
stdin = sys.stdin
sys.setrecursionlimit(10**6)
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

n = ni()
A = na()

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

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

dp = [1]*(n+1)
pd = [1]*(n+1)

m = 1
for i in range(1,n+1):
    m = m*2
    dp[i] = m
    m -= A[i]
    if m < 0:
        print(-1)
        exit()

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

ans = []
for i in range(n+1):
    ans.append(min(dp[i],pd[i]))
    
print(sum(ans))

Solution (Python):
N=int(input())
A=list(map(int,input().split()))
B=[0]*(N+1)
B[N]=A[N]
for i in range(N-1,-1,-1):
    B[i]=B[i+1]+A[i]

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

check=[min(B[i],C[i]) for i in range(N+1)]
for i in range(N+1):
    if check[i]<A[i]:
        print(-1)
        exit()
print(sum(check))

Solution (Python):
N = int(input())
A= list(map(int, input().split()))
S = sum(A)
ans = 0
leaf = 1
S_now = 0

if A[0] == 1:
  if N==0:
    print(1)
  else:
    print(-1)
elif A[0] != 0:
  print(-1)
else:
  for i in range(N):
    ans += leaf
    leaf -= A[i]
    S_now += A[i] 
    leaf = min(leaf*2,S-S_now)
  if A[-1] != leaf:
    print(-1)
  else:
    print(ans+A[-1])

Solution (Python):
N = int(input())
A = list(map(int, input().split()))

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

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

ans = 1
prev = 1
P = []
for a in A[1:]:
    P.append(prev)
    mx = prev * 2

    if mx < a:
        print(-1)
        exit()

    ans += mx
    prev = mx - a

while prev and P:
    ans -= prev
    pr = P.pop()
    prev = max(0, prev - pr)

print(ans)

Solution (Python):
n = int(input())
a = list(map(int, input().split()))
s = [sum(a)] * (n + 1)
now = 0
for i in range(n + 1):
    now += a[i]
    s[i] -= now
ans = 0
now = 1
for ai, si in zip(a, s):
    ans += now
    now -= ai
    if now < 0:
        print(-1)
        exit()
    now = min(now * 2, si)
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline
from itertools import accumulate
n = int(input())
a = list(map(int,input().split()))
if n == 0:
  if a[0] == 1:
    print(1)
  else:
    print(-1)
  exit()
if a[0] != 0:
  print(-1)
  exit()
ls = [0]*(n+1)
ls[0] = 1
sm = sum(a)
for i in range(1,n+1):
  if a[i] > (ls[i-1]-a[i-1])*2:
    print(-1)
    exit()
  if sm <= (ls[i-1]-a[i-1])*2:
    ls[i] = sm
    sm -= a[i]
  else:
    ls[i] = (ls[i-1]-a[i-1])*2
    sm -= a[i]
print(sum(ls))

Solution (Python):
N = int(input())
A = [int(n) for n in input().split()]

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

if A[0] != 0:
    print(-1)
    exit()
    
B = [1 for _ in range(N+1)]
for i in range(1, N+1):
    B[i] = B[i-1] * 2 - A[i]
    if B[i] < 0:
        print(-1)
        exit()

ans = 0

n_prev = 0
for a, b in zip(A[::-1], B[::-1]):
    B_low = (n_prev + 1) // 2
    B_high = n_prev

    

    if B_low > b:
        print(-1)
        exit()

    n_cur = a + min(B_high, b)
    
    ans += n_cur
    n_prev = n_cur
    
print(ans)

Solution (Python):
n = int(input())
a = list(map(int,input().split()))

div_count = sum(a)-1
node = 1
ans = 0
for i,ai in enumerate(a):
    ans += node
    
    if ai > node:
        ans = -1
        break
    else:
        div_num = min(node - ai, div_count)
        node = div_num + (node - ai)
        div_count -= div_num

print(ans)

Solution (Python):
n = int(input())
a = list(map(int,input().split()))
b = [0]
for i in range(n+1):
  b.append(b[-1]+a[-1-i])
b.reverse()
b.pop()


now = 1
ans = 0
for i in range(n+1):
  if now > b[i]:
    now = b[i]
  ans += now
  now -= a[i]
  if now <= 0 and i != n:
    print(-1)
    exit()
  if now < 0 and i == n:
    print(-1)
    exit()
  if now == 0 and i == n:
    print(ans)
    exit()
  now *= 2

Solution (Python):
N = int(input())
A = list(map(int, input().split()))

left = sum(A)
n = 1
ans = 1
for a in A:
  left -= a
  if a > n or n - a > left:
    print(-1)
    break
  n = min((n - a) * 2, left)
  ans += n
else:
  if n > 0:
    print(-a)
  else:
    print(ans)

Solution (Python):
n = input()
vs = list( map(int,input().split(" ")) )
def cal(vs):
    if len(vs)==1:
        if vs[0]==1:
            return 1
        else:
            return -1
    if vs[0]>0:
        return -1
    x = 1
    rem_sum = sum(vs)
    res = [1]
    for v in vs[1:]:
        x = min(2*x, rem_sum)
        res.append(x)
        x -= v
        rem_sum -= v
        if x<0:return -1
    
    return sum(res)
print(cal(vs))

Solution (Python):
import sys
sys.setrecursionlimit(10**8)
input = sys.stdin.readline

N = int(input())
A = list(map(int,input().split()))

if N!=0 and A[0]!=0:
    print(-1)
    exit()
elif N==0:
    if A[0]==1:
        print(1)
        exit()
    else:
        print(-1)
        exit()


limit = sum(A)
ans = 1
cur = 1
for i in range(1,N+1):
    nxt = min(cur*2, limit)
    limit -= A[i]
    ans += nxt
    cur = nxt - A[i]
    if i<N and cur<=0:
        print(-1)
        exit()
if cur<0:
    print(-1)
    exit()
print(ans)

Solution (Python):
import sys

def main():
    input = sys.stdin.readline
    n = int(input())
    a = [int(x) for x in input().split()]
    
    if n == 0:
        if a[0] > 1:
            print(-1)
        else:
            print(a[0])
        sys.exit()
    
    if a[0] != 0:
        print(-1)
        sys.exit()
    
    sum_a = sum(a)
    b = [0]*(n+1)
    for i in range(n):
        b[i+1] = b[i]+a[i+1]
    
    ans = 0
    key = 1
    for i in range(n+1):
        if a[i] > key:
            print(-1)
            sys.exit()
        
        ans += a[i]
        key -= a[i]
        ans += min([key, sum_a-b[i]])
        key *= 2
    
    print(ans)


if __name__ == "__main__":
    main()

Solution (Python):
n=int(input())
aa=list(map(int,input().split()))
le=1
st=0
se=10**24
for i in range(n+1):
    if(aa[i]>le):
        st=1
        break
    le-=aa[i]
    le*=2
if(st):
    print(-1)
else:
    ma=[0 for i in range(n+1)]
    ma[0]=1
    le=1
    for i in range(1,n+1):
        le*=2
        le=min(le,se)
        ma[i]=min((ma[i-1]-aa[i-1])*2,le)
    ma[n]=min(ma[n],aa[n])
    for i in range(n-1,-1,-1):
        ma[i]=min(ma[i],aa[i]+ma[i+1])
    print(sum(ma))

Solution (Python):
n = int(input())
a = [int(x) for x in input().split(' ')]

b = [0 for x in a]

x = 1
for i in range(n + 1):
    x -= a[i]
    if x < 0:
        print(-1)
        exit(0)
    b[i] = x
    x *= 2

res = 0
x = 0
for i in range(n, -1, -1):
    if (x + 1) // 2 > b[i]:
        print(-1)
        exit(0)
    x = min(x, b[i]) + a[i]
    res += x

print(res)

Solution (Python):
def solve(n, aaa):
    if n == 0:
        if aaa[0] == 1:
            return 1
        else:
            return -1
    if aaa[0] != 0:
        return -1

    hi = 1
    hi_enable = [1]
    for a in aaa[1:]:
        if hi * 2 < a:
            return -1
        hi = hi * 2 - a
        hi_enable.append(hi)
    
    vn = aaa[n]
    ans = vn
    for i in range(n - 1, -1, -1):
        hi = hi_enable[i]
        a = aaa[i]
        vn = min(vn, hi) + a
        ans += vn
        
    return ans


n = int(input())
aaa = list(map(int, input().split()))
print(solve(n, aaa))

Solution (Python):
import sys
input = sys.stdin.readline

n = int(input())
A = list(map(int,input().split()))

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

    ans = 1
    b = 0
    L = [[0,0] for i in range(n)]
    
    
    l = A[-1]
    r = A[-1]
    for i in range(n-1,-1,-1):

        L[i][0] = (l+1)//2 + A[i]
        L[i][1] = r + A[i]
        l = L[i][0]
        r = L[i][1]

    if L[0][0] != 1:
        print(-1)
    else:
        ans = 1
        now = 1
        for i in range(1, n):
            now = min(L[i][1], now*2)
            
            ans += now
            now -= A[i]
        print(ans + A[-1])

Solution (Python):
N = int(input())
A = tuple(map(int, input().split()))
limit = sum(A)
alive = 1
total = 0
for a in A:
    alive -= a
    limit -= a
    if alive < 0:
        print(-1)
        break
    total += alive + a
    alive = min(alive * 2, limit)
else:
    print(total)

Solution (Python):
import sys
n = int(input())
a = list(map(int, input().split()))

nl = sum(a)

tmp = 1
l = 0
ans = 0
for ai in a:
    ans += tmp
    if tmp < ai:
        print(-1)
        sys.exit()
    tmp -= ai
    l += ai
    if l + 2 * tmp <= nl:
        tmp *= 2
    else:
        tmp = nl - l

print(ans)

Solution (Python):
N = int(input()) + 1
A = list(map(int, input().split()))

B = [0] * N
for i in reversed(range(N)):
    if i == N - 1:
        B[i] = A[i]
    else:
        B[i] = B[i + 1] + A[i]

if A[0] >= 2:
    print(-1)
    exit(0)

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

m = 1 
ans = 1
for i in range(1, N):
    m = min((m - A[i - 1]) * 2, B[i])
    if m < A[i]:
        print(-1)
        exit(0)
    ans += m
print(ans)

Solution (Python):
import sys
input = sys.stdin.readline

N = int(input())
A = list(map(int, input().split()))
if N == 0:
    if A[0] == 1:
        print(1)
        exit()
    else:
        print(-1)
        exit()
if A[0] != 0:
    print(-1)
    exit()
cum = [0] * (N+2)
for i in range(N+1)[::-1]:
    cum[i] = cum[i+1] + A[i]
ans = 1
cur = 1
for i in range(1, N+1):
    cur = min(cur * 2, cum[i+1] + A[i])
    ans += cur
    cur -= A[i]
    if cur < 0:
        print(-1)
        exit()
print(ans)

Solution (Python):
if __name__ == '__main__':
    from sys import stdin
    
    
    
    
    
    
    input = stdin.readline

    n = int(input())
    aa = list(map(int, input().split()))

    left_leaves = sum(aa)
    ans = 0
    now = 1
    for i in range(n):
        ans += now
        num_of_node = now - aa[i]
        if num_of_node <= 0:
            print(-1)
            exit()
        max_next_node = num_of_node*2
        left_leaves -= aa[i]
        if max_next_node > left_leaves:
            now = left_leaves
        else:
            now = max_next_node
    ans += now
    if now-aa[-1] != 0:
        print(-1)
    else:
        print(ans)

Solution (Python):

import sys

N, *A = map(int, sys.stdin.buffer.read().split())

def tree(A,N):
  m = [A[i] for i in range(N+1)]
  M = [A[i] for i in range(N+1)]
  for i in range(N-1,-1,-1):
    m[i] += m[i+1]//2+m[i+1]%2
    M[i] += M[i+1]
  if m[0]>1 or M[0]==0:
    return -1
  count = 1
  vertex = 1
  for i in range(1,N+1):
    vertex = min(2*(vertex-A[i-1]), M[i])
    count += vertex
  return count
      
print(tree(A,N))

Solution (Python):
n = int(input())
a = list(map(int,input().split()))

count = sum(a) - 1
tmp = 1
ans = 1

if len(a) == 1:
    if a[0] == 1:
        print(1)
        exit()
    else:
        print(-1)
        exit()
elif a[0] != 0:
    print(-1)
    exit()

for i in range(1,n+1):
    a1 = a[i]
    if count >= tmp:
        count -= tmp
        tmp *= 2
        ans += tmp
    else:
        tmp += count
        count = 0
        ans += tmp
    if tmp >= a1:
        tmp -= a1
    else:
        print(-1)
        exit()

print(ans)

Solution (Python):
def main():
    n = int(input())
    a = list(map(int, input().split()))

    section_needed = sum(a)
    ans = 0
    section_count = 1
    total_section = 1
    for i in range(n+1):
        ans += section_count
        section_count -= a[i]
        if section_count <= 0 and i != n:
            print(-1)
            return
        if i == n and total_section != section_needed:
            print(-1)
            return
        next_branch = min(max(0, section_needed - total_section), section_count)
        total_section += next_branch
        section_count += next_branch

    print(ans)

if __name__ == '__main__':
    main()

Solution (Python):
n = int(input())
a = [int(i) for i in input().split()]
if n == 0 and a[0] == 1:
    print(1)
    exit()
b = []
i = 0
for j in reversed(a):
    i += j
    b.append(i)
b.reverse()
ans = 1
if a[0] != 0:
    print(-1)
    exit()
i = 1
for j, k in zip(a[1:], b[1:]):
    if j > i*2:
        print(-1)
        exit()
    i = min(k, i * 2) - j
    ans += i + j
    if i < 0:
        print(-1)
        exit()
print(ans)

Solution (Python):
mod = 1000000007
eps = 10**-9


def main():
    import sys
    input = sys.stdin.readline

    N = int(input())
    A = list(map(int, input().split()))

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

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

    B = [0] * (N+1)
    B[N] = A[N]
    for i in range(N-1, -1, -1):
        B[i] = B[i+1] + A[i]
    C = [0] * (N+1)
    for i in range(N+1):
        if i == 0:
            B[0] = 1
            C[0] = 1
        else:
            if B[i] > C[i-1] * 2:
                B[i] = C[i-1] * 2
            C[i] = B[i] - A[i]
            if C[i] < 0:
                print(-1)
                exit()
    print(sum(B))


if __name__ == '__main__':
    main()

Solution (Python):
N = int(input())
A = [int(a) for a in input().split()]
MA = [0] * (N + 2)
MA[0] = 1
ma = 1
for i, a in enumerate(A):
    if a > ma or (a == ma and i < N - 1):
        print(-1)
        exit()
    ma = (ma - a) * 2
    MA[i+1] = ma

ans = 0
s = 0
for i in range(N + 1)[::-1]:
    a = A[i]
    s = min(s + a, MA[i])
    ans += s
print(ans)