def chain(n, a): if n==1: return 0 i=0 t=0 while (n>1): for _ in range(a[i]): t += 1 n -= 1 if n==1: return t i += 1 n-=1
return t