def solve():
    n=int(input())
    a=[int(x) for x in input().split()]
    b=[int(x) for x in input().split()]
    li=list(a)
    d={}
    for i in range(n):
        if d.get(a[i],0)==0:
            d[a[i]]=[i]
        else:
            temp=d[a[i]]
            temp.append(i)
            d[a[i]]=temp
    li.sort()
    for i in range(n):
        if a[i]!=li[i]:
            x=b[i]
            temp=d[li[i]]

            for ele in temp:
                if b[ele]!=x:
                    a[i],a[ele]=a[ele],a[i]
                    b[i],b[ele]=b[ele],b[i]
                    note=ele
                    break
            else:
                print('No')
                return
    else:
        print('Yes')
        return
t=int(input())
for i in range(t):
    solve()


t=int(input())
for _ in range(t):
    n=int(input())
    a=list(map(int,input().split()))
    b = list(map(int, input().split()))
    l0=[]
    l1=[]
    for i in range(n):
        if b[i]==0:
            l0.append(a[i])
        else:
            l1.append(b[i])
    n0=len(l0)
    n1=len(l1)
    res='Yes'
    for i in range(max(n0-1,n1-1)):
        if i<n0-1:
            if l0[i+1]<l0[i]:
                res='No'
                break
        if i<n1-1:
            if l1[i+1]<l1[i]:
                res='No'
                break
    print(res)


t=int(input())
for _ in range(t):
    n=int(input())
    a=list(map(int,input().split()))
    b = list(map(int, input().split()))
    res='Yes'
    for i in range(n-1):
        for j in range(i+1,n):
            if a[i]>a[j] and b[i]==b[j]:
                res='No'
                break
    print(res)


t=int(input())
for _ in range(t):
    n=int(input())
    a=list(map(int,input().split()))
    b = list(map(int, input().split()))
    l0=[]
    l1=[]
    for i in range(n):
        if b[i]==0:
            l0.append(a[i])
        else:
            l1.append(a[i])
    n0=len(l0)
    n1=len(l1)
    res='Yes'
    if n0==0 or n1==0:
        for i in range(max(n0-1,n1-1)):
            if i<n0-1:
                if l0[i+1]<l0[i]:
                    res='No'
                    break
            if i<n1-1:
                if l1[i+1]<l1[i]:
                    res='No'
                    break
    print(res)


t=int(input())
for _ in range(t):
    n=int(input())
    a=list(map(int,input().split()))
    b = list(map(int, input().split()))
    l0=[]
    l1=[]
    for i in range(n):
        if b[i]==0:
            l0.append(a[i])
        else:
            l1.append(a[i])
    n0=len(l0)
    n1=len(l1)
    res='Yes'
    for i in range(max(n0-1,n1-1)):
        if i<n0-1:
            if l0[i+1]<l0[i]:
                res='No'
                break
        if i<n1-1:
            if l1[i+1]<l1[i]:
                res='No'
                break
    print(res)


t = int(input())
for _ in range(t):
    n = int(input())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    for i in range(len(a)-1):
        if a[i] > a[i+1] and b[i] != b[i+1]:
            auxi = a[i]
            a[i] = a[i+1]
            a[i+1] = auxi

            auxb = b[i]
            b[i] = b[i+1]
            b[i+1]=auxb

    aux = a.copy()
    a.sort()
    if a == aux:
        print("yes")
    else:
        print("no")


t = int(input())
for _ in range(t):
    n = int(input())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    for j in range(len(a)-1):
        for i in range(len(a)-1):
            if a[i] > a[i+1] and b[i] != b[i+1]:
                auxi = a[i]
                a[i] = a[i+1]
                a[i+1] = auxi

                auxb = b[i]
                b[i] = b[i+1]
                b[i+1]=auxb

    flag = False
    for i in range(len(a)-1):
        if a[i] <= a[i+1]:
            flag = True
        else:
            flag = False
            break
    if flag:
        print("yes")
    else:
        print("no")


t = int(input())
for _ in range(t):
    n = int(input())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    one = 0
    zero = 0
    flag = True
    for i in b:
        if i == 1:
            one+=1
        else:
            zero+=1
    if zero > 0 and one == 0 or zero == 0 and one > 0:
        aux = a.copy()
        a.sort()
        if aux==a:
            print("yes")
        else:
            print("no")
    else:
        print("yes")


t = int(input())
for _ in range(t):
    n = int(input())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    for i in range(len(a)-1):
        if a[i] > a[i+1] and b[i] != b[i+1]:
            auxi = a[i]
            a[i] = a[i+1]
            a[i+1] = auxi

            auxb = b[i]
            b[i] = b[i+1]
            b[i+1]=auxb

    flag = False
    for i in range(len(a)-1):
        if a[i] <= a[i+1]:
            flag = True
        else:
            flag = False
            break
    if flag:
        print("yes")
    else:
        print("no")


t=int(input())
for i in range(t):
    n=int(input())
    A=[int(i) for i in input().split()]
    B=[int(i) for i in input().split()]
    a=sorted(A)
    Z=[]
    for i in range(n):
        if A[i]!=a[i]:
            Z.append(A[i])
    flag=1
    if len(Z)==0:
        print("Yes")
    else:
        Z.sort()
        for i in range(1,len(Z)):
            j=A.index(Z[i])
            k=A.index(Z[i-1])
            if k<=j:
                None
            else:
                if B[j]+B[k]==1:
                    None
                else:
                    flag=0
        if flag==0:
            print("No")
        else:
            print("Yes")


t=int(input())
for i in range(t):
    n=int(input())
    A=[int(i) for i in input().split()]
    B=[int(i) for i in input().split()]
    B=set(B)
    if A==sorted(A):
        print("Yes")
    else:
        if len(B)>1:
            print("Yes")
        else:
            print("No")


t=int(input())
for i in range(t):
    n=int(input())
    A=[int(i) for i in input().split()]
    B=[int(i) for i in input().split()]
    arr0=[]
    arr1=[]
    for i in range(n):
        if B[i]==0:
            arr0.append(A[i])
        else:
            arr1.append(A[i])
    '''print(arr0)
    print(arr1)'''
    if arr0==sorted(arr0) and arr1==sorted(arr1):
        print("Yes")
    else:
        print("No")


def bubbleSort(n, arr, blist):
    tags = list(range(n))
    tagtype = dict()
    for ind, elem in enumerate(tags):
        tagtype[elem] = blist[ind]

    for i in range(n-1):
        for j in range(0, n-i-1):
            if arr[j] > arr[j+1]:
                if tagtype[tags[j]]==tagtype[tags[j+1]]:
                    flag = 0
                    for k in range(j+2, n-i-1):
                        if arr[j] > arr[k] and tagtype[tags[j]]!=tagtype[tags[k]]:
                            arr[j], arr[k] = arr[k], arr[j]
                            tags[j], tags[k] = tags[k], tags[j]
                            flag = 1
                            break
                    if flag:
                        continue
                    else:
                        return ('No', arr, tags, tagtype)
                else:
                    arr[j], arr[j+1] = arr[j+1], arr[j]
                    tags[j], tags[j+1] = tags[j+1], tags[j]

    return ('Yes', arr, tags, tagtype)

from sys import stdin, stdout
t = int(input())
for _ in range(t):
    n = int(input())
    alist = list(map(int, stdin.readline().strip().split()))
    blist = list(map(int, stdin.readline().strip().split()))

    ans = bubbleSort(n, alist, blist)
    if ans[0] == 'Yes':
        print(ans[0])
    else:
        print(ans[0])
        # _, arr, tags, tagype = ans


from sys import stdin, stdout
t = int(input())
for _ in range(t):
    n = int(input())
    alist = list(map(int, stdin.readline().strip().split()))
    blist = list(map(int, stdin.readline().strip().split()))

    if alist == sorted(alist):
        print('Yes')
    else:
        if 1 in blist and 0 in blist:
            print('Yes')
        else:
            print('No')


def bubbleSort(n, arr, blist):
    tags = list(range(n))
    tagtype = dict()
    for ind, elem in enumerate(tags):
        tagtype[elem] = blist[ind]

    for i in range(n-1):
        for j in range(0, n-i-1):
            if arr[j] > arr[j+1] :
                arr[j], arr[j+1] = arr[j+1], arr[j]
                tags[j], tags[j+1] = tags[j+1], tags[j]
                if tagtype[tags[j]]==tagtype[tags[j+1]]:
                    return 'No'

    return 'Yes'

from sys import stdin, stdout
t = int(input())
for _ in range(t):
    n = int(input())
    alist = list(map(int, stdin.readline().strip().split()))
    blist = list(map(int, stdin.readline().strip().split()))

    print(bubbleSort(n, alist, blist))


from sys import stdin, stdout
t = int(input())
for _ in range(t):
    n = int(input())
    alist = list(map(int, stdin.readline().strip().split()))
    blist = list(map(int, stdin.readline().strip().split()))

    if alist == sorted(alist):
        print('Yes')
    else:
        if 1 in blist:
            print('Yes')
        else:
            print('No')


for _ in range(int(input())):
    n = int(input())
    a = [int(x) for x in input().split()]
    b = [int(x) for x in input().split()]
    if (1 not in b or 0 not in b) and sorted(a) != a:
        print("NO")
    else:
        print("YES")


for _ in range(int(input())):
    n = int(input())
    a = [int(x) for x in input().split()]
    b = [int(x) for x in input().split()]
    if a == sorted(a):
        print("YES")
    else:
        zero = b.count(0)
        one = b.count(1)
        if one > 0 and zero > 0:
            print("YES")
        else:
            print("NO")


for _ in range(int(input())):
    n = int(input())
    a = [int(x) for x in input().split()]
    b = [int(x) for x in input().split()]
    o, z = b.count(1), b.count(0)
    if a == sorted(a) or o != 0 and z != 0:
        print("YES")
    else:
        print("NO")


for _ in range(int(input())):
    n=int(input())
    l1=list(map(int,input().split()))
    l2=list(map(int,input().split()))
    r=[]
    for i in l1:
        r.append(l1)
    if(r==l1.sort()):
        print("Yes")
    elif((0 in l2) and (1 in l2)):
        print("Yes")
    else:
        print("No")


for _ in range(int(input())):
    n=int(input())
    l1=list(map(int,input().split()))
    l2=list(map(int,input().split()))
    r=[]
    for i in l1:
        r.append(i)
    l1.sort()
    if((0 in l2) and (1 in l2)):
        print("Yes")
    elif(r==l1):
        print("Yes")
    else:
        print("No")


for _ in range(int(input())):
    n=int(input())
    l1=list(map(int,input().split()))
    l2=list(map(int,input().split()))
    r=l2.count(l2[0])==len(l2)
    m=[]
    for i in l1:
        m.append(i)
    if(l1.sort()==l1):
        print("Yes")
    elif(r and m!=l1):
        print("No")
    else:
        for i in range(n):
            for j in range(i+1,n):
                if(m[i]>m[j] and l2[i]!=l2[j]):
                    t=m[i]
                    m[i]=m[j]
                    m[j]=t
                    t1=l2[i]
                    l2[i]=l2[j]
                    l2[j]=t

        if(m==l1):
            print("Yes")
        else:
            print("No")


for _ in range(int(input())):
    n=int(input())
    l1=list(map(int,input().split()))
    l2=list(map(int,input().split()))
    r=l2.count(l2[0])==len(l2)
    m=[]
    for i in l1:
        m.append(i)
    if(l1.sort()==l1):
        print("Yes")
    elif(r and m!=l1):
        print("No")
    else:
        for i in range(n):
            for j in range(i+1,n):
                if(m[i]>m[j] and l2[i]!=l2[j]):
                    t=m[i]
                    m[i]=m[j]
                    m[j]=t
                    t1=l2[i]
                    l2[i]=l2[j]
                    l2[j]=t1

        if(m==l1):
            print("Yes")
        else:
            print("No")


from random import randint, random

for _ in range(int(input())):
    n = int(input())
    # a = [randint(0, 1000) for _ in range(n)]
    # b = [int(random() < 0.5) for _ in range(n)]
    # print(a)
    # print(b)
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))

    if (sum(b) == len(b) or sum(b) == 0) and sorted(a) != a and len(a) > 1:
        print('No')
    else:
        print('Yes')


for _ in range(int(input())):
    input()
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    if (sum(b) == list(b) or sum(b)) == 0 and sorted(a) != a:
        print('No')
    else:
        print('Yes')


for _ in range(int(input())):
    input()
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    if (sum(b) == list(b) or sum(b)) == 0 and sorted(a) != a and len(a) > 1:
        print('No')
    else:
        print('Yes')


for _ in range(int(input())):
    n= int(input())
    a = list(map(int,input().split()))
    b = list(map(int,input().split()))
    d={0:[],1:[]}
    for i in range(n):
        if b[i]==0:
            d[0].append(a[i])
        else:
            d[1].append(a[i])
    sor_zero = sorted(d[0])
    sor_one= sorted(d[1])
    if(len(d[0])>0 and len(d[1])>0):
        print("Yes")
    else:
        if(d[0]==0):
            if(sor_one == d[1]):
                print("Yes")
            else:
                print("No")
        else:
            if(sor_zero == d[0]):
                print("Yes")
            else:
                print("No")


for _ in range(int(input())):
    n= int(input())
    a = list(map(int,input().split()))
    b = list(map(int,input().split()))
    d={0:[],1:[]}
    for i in range(n):
        if b[i]==0:
            d[0].append(a[i])
        else:
            d[1].append(a[i])

    if(len(d[0])>0 and len(d[1])>0):
        print("Yes")
    else:
        if(len(d[0])==0):
            sor_one= sorted(d[1])
            if(sor_one == d[1]):
                print("Yes")
            else:
                print("No")
        else:
            sor_zero = sorted(d[0])
            if(sor_zero == d[0]):
                print("Yes")
            else:
                print("No")


for _ in range(int(input())):
    n= int(input())
    a = list(map(int,input().split()))
    b = list(map(int,input().split()))
    d={0:[],1:[]}
    for i in range(n):
        if b[i]==0:
            d[0].append(a[i])
        else:
            d[1].append(a[i])
    sor_zero = sorted(d[0])
    sor_one= sorted(d[1])
    if(sor_zero==d[0] and sor_one==d[1]):
        print("Yes")
    else:
        print("No")


t = int(input())
for _ in range(t):
    n = int(input())
    a = [int(i) for i in input().split()]
    b = [int(i) for i in input().split()]
    sorteda = sorted(a)
    if a == sorteda:
        print('yes')
    else:
        j = 0
        count = 0
        while a != sorteda and count < n:
            mn = sorteda[j]
            idx = a.index(mn)
            for i in range(n):
                if i < idx and a[i] > a[idx] and b[i] != b[idx]:
                    temp = a[i]
                    a[i] = a[idx]
                    a[idx] = temp
                    temp = b[i]
                    b[i] = b[idx]
                    b[idx] = temp
            j += 1
            if j == n:
                j = 0
                count += 1
        print('yes' if a == sorteda else 'no')


t = int(input())
for _ in range(t):
    n = int(input())
    a = [int(i) for i in input().split()]
    b = [int(i) for i in input().split()]
    sorteda = sorted(a)
    if a == sorteda:
        print('yes')
    else:
        j = 0
        count = 0
        while a != sorteda and count < 2:
            mn = sorteda[j]
            idx = a.index(mn)
            for i in range(n):
                if i < idx and a[i] > a[idx] and b[i] != b[idx]:
                    temp = a[i]
                    a[i] = a[idx]
                    a[idx] = temp
                    temp = b[i]
                    b[i] = b[idx]
                    b[idx] = temp
            j += 1
            if j == n:
                j = 0
                count += 1
        print('yes' if a == sorteda else 'no')


t = int(input())
for _ in range(t):
    n = int(input())
    a = [int(i) for i in input().split()]
    b = [int(i) for i in input().split()]
    sorteda = sorted(a)
    if a == sorteda:
        print('yes')
    else:
        done = False
        while not done:
            done = True
            for i in range(n):
                for j in range(i+1, n):
                    if a[i] > a[j] and b[i] != b[j]:
                        temp = a[i]
                        a[i] = a[j]
                        a[j] = temp
                        temp = b[i]
                        b[i] = b[j]
                        b[j] = temp
                        done = False
                if a == sorteda:
                    done = True
                    break
        print('yes' if a == sorteda else 'no')


t = int(input())
for _ in range(t):
    n = int(input())
    a = [int(i) for i in input().split()]
    b = [int(i) for i in input().split()]
    sorteda = sorted(a)
    if a == sorteda:
        print('yes')
    else:
        j = 0
        count = 0
        while a != sorteda and count < n*n:
            mn = sorteda[j]
            idx = a.index(mn)
            for i in range(n):
                if i < idx and a[i] > a[idx] and b[i] != b[idx]:
                    temp = a[i]
                    a[i] = a[idx]
                    a[idx] = temp
                    temp = b[i]
                    b[i] = b[idx]
                    b[idx] = temp
            j += 1
            if j == n:
                j = 0
                count += 1
        print('yes' if a == sorteda else 'no')


t = int(input())
for _ in range(t):
    n = int(input())
    a = [int(i) for i in input().split()]
    b = [int(i) for i in input().split()]
    sorteda = sorted(a)
    if a == sorteda:
        print('yes')
    elif 0 in b and 1 in b:
        print('yes')
    else:
        print('no')


t = int(input())
for _ in range(t):
    n = int(input())
    a = [int(i) for i in input().split()]
    b = [int(i) for i in input().split()]
    sorteda = sorted(a)
    if a == sorteda:
        print('yes')
    else:
        j = 0
        count = 0
        while a != sorteda and count < 2*n:
            mn = sorteda[j]
            idx = a.index(mn)
            for i in range(n):
                if i < idx and a[i] > a[idx] and b[i] != b[idx]:
                    temp = a[i]
                    a[i] = a[idx]
                    a[idx] = temp
                    temp = b[i]
                    b[i] = b[idx]
                    b[idx] = temp
            j += 1
            if j == n:
                j = 0
                count += 1
        print('yes' if a == sorteda else 'no')


t = int(input())
for _ in range(t):
    n = int(input())
    a = [int(i) for i in input().split()]
    b = [int(i) for i in input().split()]
    sorteda = sorted(a)
    if a == sorteda:
        print('yes')
    else:
        done = False
        while not done:
            done = True
            for i in range(n):
                for j in range(i+1, n):
                    if a[i] > a[j] and b[i] != b[j]:
                        temp = a[i]
                        a[i] = a[j]
                        a[j] = temp
                        b[i] = temp
                        b[i] = b[j]
                        b[j] = temp
                        done = False
                if a == sorteda:
                    done = True
                    break
        print('yes' if a == sorteda else 'no')


x,y=int,input
r=lambda a:list(map(x,a.split()))
for i in range(x(y())):
    n,a,b=x(y()),r(y()),r(y())
    print("No\n"if b.count(1)in [0,n]and a!=sorted(a)else"Yes\n")


x,y=int,input
for i in range(x(y())):
    n=x(y())
    a=list(map(x,y().split()))
    b=list(map(x,y().split()))
    print("No\n"if b.count(1)in [0,n]and a!=sorted(a)else"Yes\n")


r=lambda:list(map(int,input().split()))
for _ in range(r()[0]):
    n,a,b=r(),r(),r()
    print("No\n"if b.count(1)in [0,n]and a!=sorted(a)else"Yes\n")


r=lambda:list(map(int,input().split()))
for _ in range(r()[0]):
    n,a,b=r()[0],r(),r()
    print("No\n"if b.count(1)in [0,n]and a!=sorted(a)else"Yes\n")


x,y=int,input
r=lambda a:list(map(x,a.split()))
for i in range(x(y())):
    n,a,b=y(),r(y()),r(y())
    print("No\n"if b.count(1)in [0,n]and a!=sorted(a)else"Yes\n")


r=lambda:list(map(int,input().split()))
for _ in range(r()[0]):
    n,a,b=r()[0],r(),r()
    print("YNeos"[sum(b)%n==0 and a!=sorted(a)::2])


r=lambda:list(map(int,input().split()))
for _ in[0]*r()[0]:
 n,a,b=r()[0],r(),r()
 print("YNeos"[sum(b)%n==0and a!=sorted(a)::2])


x,y=int,input
r=lambda a:list(map(x,a.split()))
for i in range(x(y())):
    n=x(y())
    a,b=r(y()),r(y())
    print("No\n"if b.count(1)in [0,n]and a!=sorted(a)else"Yes\n")


r=lambda:list(map(int,input().split()))
for _ in range(r()[0]):
 n,a,b=r()[0],r(),r()
 print("YNeos"[sum(b)%n==0 and a!=sorted(a)::2])


r=lambda:list(map(int,input().split()))
for _ in range(r()[0]):
    n,a,b=r()[0],r(),r()
    print("YNeos"[b.count(1)%n==0 and a!=sorted(a)::2])


r=lambda:list(map(int,input().split()))
for _ in range(r()[0]):
    n,a,b=r()[0],r(),r()
    print("YNeos"[b.count(1)in [0,n]and a!=sorted(a)::2])


r=lambda:list(map(int,input().split()))
for _ in range(r()[0]):
 n,a,b=r()[0],r(),r()
 print("YNeos"[sum(b)%n==0and a!=sorted(a)::2])


# -*- coding: utf-8 -*-
"""
Created on Sun Jun  7 20:43:23 2020

@author: lenovo
"""
def bubbleSort(arr, k):
    n = len(arr)

    # Traverse through all array elements
    for i in range(n-1):
        for j in range(0, n-i-1):

            if(arr[j] > arr[j+1]):
                if(k[j]^k[j+1]==1):
                    k[j], k[j+1] = k[j+1], k[j]
                    arr[j], arr[j+1] = arr[j+1], arr[j]

n = int(input())

for i in range(0, n):
    y = int(input())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    z = [0]*y
    for j in range(0, y):
    	z[j] = a[j]
    a.sort()
    bubbleSort(z, b)
    if(z==a):
        print("Yes")
    else:
        print("No")


# -*- coding: utf-8 -*-
"""
Created on Sun Jun  7 20:43:23 2020

@author: lenovo
"""
def bubbleSort(arr, k):
    x = len(arr)
    if(x==1):
    	return True
    for i in range(x-1):
        for j in range(0, x-i-1):

            if(arr[j] > arr[j+1]):
                if(k[j]^k[j+1]==1):
                    k[j], k[j+1] = k[j+1], k[j]
                    arr[j], arr[j+1] = arr[j+1], arr[j]
                else:
                    return False
    return True

n = int(input())

for i in range(0, n):
    y = int(input())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    status = bubbleSort(a, b)
    if (status):
        print("Yes")
    else:
        print("No")


# -*- coding: utf-8 -*-
"""
Created on Sat Jun  6 21:00:34 2020

@author: lenovo
"""

n = int(input())

for i in range(0, n):
    y = int(input())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    countA = 0
    countB = 0
    z = [0]*y
    for j in range(0, y):
        a[j]=z[j]
    for j in range(0, y):
        if(b[j]==0):
            countA +=1
        else:
            countB +=1
    if(countA>=1 and countB>=1):
        print("Yes")
    else:
        if(z.sort==a):
            print("Yes")
        else:
            print("No")


# -*- coding: utf-8 -*-
"""
Created on Sat Jun  6 21:00:34 2020

@author: lenovo
"""

n = int(input())

for i in range(0, n):
    y = int(input())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    countA = 0
    countB = 0
    z = [0]*y
    for j in range(0, y):
        z[j] = a[j]
    for j in range(0, y):
        if(b[j]==0):
            countA +=1
        else:
            countB +=1
    z.sort()
    if(countA>=1 and countB>=1):
        print("Yes")
    else:
        if(z==a):
            print("Yes")
        else:
            print("No")


# -*- coding: utf-8 -*-
"""
Created on Sat Jun  6 21:00:34 2020

@author: lenovo
"""

n = int(input())

for i in range(0, n):
    y = int(input())
    a = list(map(int, input().spli()))
    b = list(map(int, input().spli()))
    countA = 0
    countB = 0
    for j in range(0, n):
        if(b(j)==0):
            countA +=1
        else:
            countB +=1
    if(countA>=1 and countB>=1):
        print("Yes")
    else:
        print("No")


# -*- coding: utf-8 -*-
"""
Created on Sat Jun  6 21:00:34 2020

@author: lenovo
"""

n = int(input())

for i in range(0, n):
    y = int(input())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    countA = 0
    countB = 0
    z = [0]*y
    for j in range(0, y):
        a[j]=z[j]
    for j in range(0, y):
        if(b[j]==0):
            countA +=1
        else:
            countB +=1
    z.sort()
    if(countA>=1 and countB>=1):
        print("Yes")
    else:
        if(z==a):
            print("Yes")
        else:
            print("No")


# -*- coding: utf-8 -*-
"""
Created on Sat Jun  6 21:00:34 2020

@author: lenovo
"""

n = int(input())

for i in range(0, n):
    y = int(input())
    a = list(map(int, input().spli()))
    b = list(map(int, input().spli()))
    countA = 0
    countB = 0
    for j in range(0, y):
        if(b(j)==0):
            countA +=1
        else:
            countB +=1
    if(countA>=1 and countB>=1):
        print("Yes")
    else:
        print("No")


# -*- coding: utf-8 -*-
"""
Created on Sun Jun  7 20:43:23 2020

@author: lenovo
"""
def mySort(arr, k):
    x = len(arr)
    if(x==1):
    	return True
    for i in range(x-1):
        for j in range(0, x-i-1):

            if(arr[j] > arr[x-i-1]):
                if(k[j]^k[x-i-1]==1):
                    k[j], k[x-i-1] = k[x-i-1], k[j]
                    arr[j], arr[x-i-1] = arr[x-i-1], arr[j]
                else:
                    return False
    return True
def bubbleSort(arr, k):
    x = len(arr)
    if(x==1):
    	return True
    for i in range(x-1):
        for j in range(0, x-i-1):

            if(arr[j] > arr[j+1]):
                if(k[j]^k[j+1]==1):
                    k[j], k[j+1] = k[j+1], k[j]
                    arr[j], arr[j+1] = arr[j+1], arr[j]
                else:
                    return False
    return True

n = int(input())

for i in range(0, n):
    y = int(input())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    status = bubbleSort(a, b)
    if(status== False):
    	status= mySort(a, b)
    if (status):
        print("Yes")
    else:
        print("No")


# -*- coding: utf-8 -*-
"""
Created on Sun Jun  7 20:43:23 2020

@author: lenovo
"""
def bubbleSort(arr, k):
    x = len(arr)
    for i in range(x-1):
        for j in range(0, x-i-1):

            if(arr[j] > arr[j+1]):
                if(k[j]^k[j+1]==1):
                    k[j], k[j+1] = k[j+1], k[j]
                    arr[j], arr[j+1] = arr[j+1], arr[j]
                else:
                    return False
    return True

n = int(input())

for i in range(0, n):
    y = int(input())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    status = bubbleSort(a, b)
    if (status):
        print("Yes")
    else:
        print("No")


# -*- coding: utf-8 -*-
"""
Created on Sat Jun  6 21:00:34 2020

@author: lenovo
"""

n = int(input())

for i in range(0, n):
    y = int(input())
    a = list(map(int, input().split()))
    b = list(map(int, input().split()))
    countA = 0
    countB = 0
    for j in range(0, y):
        if(b[j]==0):
            countA +=1
        else:
            countB +=1
    if(countA>=1 and countB>=1):
        print("Yes")
    else:
        print("No")


def bubbleSort(arr,br):
    n = len(arr)

    for i in range(n):
        swapped = False

        for j in range(0, n-i-1):

            if arr[j] > arr[j+1] and br[j]!=br[j+1]:
                arr[j], arr[j+1] = arr[j+1], arr[j]
                br[j],br[j+1]= br[j+1], br[j]
                swapped = True

        if swapped == False:
            break

    return arr

t=int(input())
while t:
    t-=1
    n=int(input())
    ar=list(map(int,input().split()))
    br=list(map(int,input().split()))

    temp=ar.copy()
    # temp.sort()

    bubbleSort(temp,br)
    ar.sort()

    # print(temp,ar)

    if ar==temp:
        print('yes')
    else:
        print('no')


t=int(input())
while t:
    t-=1
    n=int(input())
    ar=list(map(int,input().split()))
    br=list(map(int,input().split()))

    print('yes' if len(set(br))>1 or ar==sorted(ar) else 'no')


//
//  main.cpp
//  Hello
//
//  Created by Gasser Mamdouh on 29/10/2019.
//  Copyright © 2019 Gasser Mamdouh. All rights reserved.
//

#include <iostream>
#include <map>
#include <utility>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <stdlib.h>
#include <string.h>
#include <list>
#include <set>
#include <stdio.h>
#include <numeric>

using namespace std;

int main(){
    int n, cnt = 0;
    cin >> n;
    vector<int> arr(n);
    for(int i = 0; i < n; i++){
        cin >> arr[i];
        cnt += arr[i];
    }
    if(cnt == 1){
        cout << "-1" << endl;
        return 0;
    }
    int k = 2;
    for(; cnt % k != 0; k++);

    int curCarry = 0, ans = 0;
    for(int i = 0; i < n; i++){
        if(curCarry != 0){
            ans++;
        }
        curCarry += arr[i];
        if(curCarry == k){
            curCarry = 0;
        }
    }
    cout << ans << endl;
    return 0;
}


#include<bits/stdc++.h>
#define LL long long
#define pb push_back
using namespace std;
const int N=1e6+50;
int n,a[N];LL S,ans=1e18;
void upd(LL x){
	if(x==1)return;
	LL ret=0,now=0;
	for(int i=1;i<n;i++){
		now+=a[i];now%=x;
		ret+=min(now,x-now);
		if(ret>=ans)return;
	}
	ans=ret;
}
vector<int>v;
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++)scanf("%d",&a[i]),S+=a[i];
	for(int i=1;1ll*i*i<=S;i++)
		v.pb(i),v.pb(S/i);
	random_shuffle(v.begin(),v.end());
	for(int i=0;i<v.size();i++)upd(v[i]);
	cout<<(ans==1e18?-1:ans);
	return 0;
}


#include<bits/stdc++.h>
#define LL long long
#define pb push_back
using namespace std;
const int N=1e6+50;
int n,a[N];LL S,ans=1e18;
void upd(LL x){
	if(x==1)return;
	LL ret=0,now=0;
	for(int i=1;i<n;i++){
		now+=a[i];now%=x;
		ret+=min(now,x-now);
		if(ret>=ans)return;
	}//cout<<x<<" "<<ret<<endl;
	ans=ret;
}
vector<int>v;
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++)scanf("%d",&a[i]),S+=a[i];
	for(int i=1;1ll*i*i<=S;i++)
		if(S%i==0)v.pb(i),v.pb(S/i);
	random_shuffle(v.begin(),v.end());
	for(int i=0;i<v.size();i++)upd(v[i]);
	cout<<(ans==1e18?-1:ans);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define pii pair<int,int>
#define ll long long
#define pb push_back
#define fi first
#define se second
#define mp make_pair
#define abs(x) ((x)>0?(x):-(x))
#define INF 1e18
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
   int n;
   cin>>n;
   int ara[n];
   vector<int> v,div;
   for(int i=0;i<n;i++)
    cin>>ara[i];
   for(int i=0;i<n;i++)
    if(ara[i]) v.pb(i);
    int sum=v.size();
    int k=sum;
   for(int i=2;i*i<=sum;i++)
    if(sum%i==0)
   {
       div.pb(i);
       div.pb(sum/i);
   }
   div.pb(sum);
   if(sum==1)
   {
       cout<<-1<<endl;
       return 0;
   }
ll cnt=0;
ll mn=INF;
for(int j=0;j<div.size();j++)
{
    int k=div[j];
    int mid=k/2;
    int la=0;
     cnt=0;
       while(la+1<sum)
       {
           for(int i=la;i<la+mid;i++)
            {cnt+=(v[la+mid]-v[i]);
            //cout<<cnt<<endl;
            }
           for(int i=la+mid+1;i<la+k;i++)
            {
                cnt+=(v[i]-v[la+mid]);
                //cout<<cnt<<endl;
            }
           la+=k;
       }
       //cout<<k<<' '<<cnt<<endl;
       mn=min(cnt,mn);
}
   cout<<mn<<endl;
}


#include<bits/stdc++.h>
using namespace std;
#define pii pair<int,int>
#define ll long long
#define pb push_back
#define fi first
#define se second
#define mp make_pair
#define abs(x) ((x)>0?(x):-(x))
#define INF 1e18
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
   int n;
   cin>>n;
   int ara[n];
   vector<int> v;
   for(int i=0;i<n;i++)
    cin>>ara[i];
   for(int i=0;i<n;i++)
    if(ara[i]) v.pb(i);
    int sum=v.size();
    int k=sum;
   for(int i=2;i*i<=sum;i++)
    if(sum%i==0)
   {
       k=sum/i;
       break;
   }
   if(sum==1)
   {
       cout<<-1<<endl;
       return 0;
   }
   int la=0;
int mid=k/2;
int cnt=0;
//cout<<sum<<' '<<k<<endl;
       while(la+1<sum)
       {
           for(int i=la;i<la+mid;i++)
            {cnt+=(v[la+mid]-v[i]);
            //cout<<cnt<<endl;
            }
           for(int i=la+mid+1;i<la+k;i++)
            {
                cnt+=(v[i]-v[la+mid]);
                //cout<<cnt<<endl;
            }
           la+=k;
       }
   cout<<cnt<<endl;
}


#include<bits/stdc++.h>
using namespace std;
#define pii pair<int,int>
#define ll long long
#define pb push_back
#define fi first
#define se second
#define mp make_pair
#define abs(x) ((x)>0?(x):-(x))
#define INF 1e18
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
   int n;
   cin>>n;
   int ara[n];
   vector<int> v;
   for(int i=0;i<n;i++)
    cin>>ara[i];
   for(int i=0;i<n;i++)
    if(ara[i]) v.pb(i);
    int sum=v.size();
    int k=sum;
   for(int i=2;i*i<=sum;i++)
    if(sum%i==0)
   {
       k=i;
       break;
   }
   if(sum==1)
   {
       cout<<-1<<endl;
       return 0;
   }
   int la=0;
int mid=k/2;
ll cnt=0;
//cout<<sum<<' '<<k<<endl;
       while(la+1<sum)
       {
           for(int i=la;i<la+mid;i++)
            {cnt+=(v[la+mid]-v[i]);
            //cout<<cnt<<endl;
            }
           for(int i=la+mid+1;i<la+k;i++)
            {
                cnt+=(v[i]-v[la+mid]);
                //cout<<cnt<<endl;
            }
           la+=k;
       }
   cout<<cnt<<endl;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 1e15;

const int MAXN = 1e6;
int N, A[MAXN], B[MAXN];

const int MAXP = 1e6;
bool P[MAXP+1];
vector<int> primes;

ll solve(ll d) {

	for(int i = 0; i < N; ++i) B[i] = A[i]%d;

	int l = 0, r = 0;
	ll sum = 0, ans = 0;
	for(int i = 0; i < N; ++i) {
		sum += B[i];
		r = i;

		if(sum >= d) {
			int k = l;
			ll aux = B[l];

			while(2*aux < d) {
				++k;
				aux += B[k];
			}

			for(int j = l; j <= r; ++j) if(j != k) {
				ll m = min((ll)B[j], d - B[k]);
				B[k] += m;
				B[j] -= m;
				ans += (ll)m*abs(j-k);
			}

			l = r;
			sum = B[l];
		}
	}

	return ans;
}

int main() {
	ios::sync_with_stdio(0); cin.tie(0);

	for(int i = 2; i <= MAXP; ++i) P[i] = true;

	for(int i = 2; i*i <= MAXP; ++i) if(P[i])
		for(int j = i*i; j <= MAXP; j += i) P[j] = false;

	for(int i = 2; i <= MAXP; ++i) if(P[i])
		primes.push_back(i);

	cin >> N;
	ll c = 0;

	for(int i = 0; i < N; ++i) {
		cin >> A[i];
		c += A[i];
	}

	if(c == 1) {
		cout << -1 << '\n';
		return 0;
	}

	vector<ll> D;
	for(int p : primes) if(c%p == 0) {
		D.push_back(p);
		while(c%p == 0) c /= p;
		if(c == 1) break;
	}
	if(c != 1) D.push_back(c);

	ll ans = INF;
	for(ll d : D) {
		ans = min(ans, solve(d));
	}

	cout << ans << '\n';
	return 0;
}


#include <iostream>
#include <vector>
using namespace std;

int main() {
  int n;
  cin >> n;
  int arr[n];
  int sum = 0;
  for (int i = 0; i < n; ++i) {
    cin >> arr[i];
    sum += arr[i];
  }
  if (sum == 1) {
    cout << -1;
    return 0;
  }
  int p = 2;
  for (int i = 2; i <= sum; ++i) {
    if (sum % i == 0) {
      p = i;
      break;
    }
  }
  //cout << p << endl;
  vector<int> v;
  long long ans = 0;
  for (int i = 0; i < n; ++i) {
    if (arr[i] == 1) {
      v.push_back(i);
      if (v.size() == p) {
	if (p == 2) {
	  ans += v[1] - v[0];
	} else {
	  for (int j = 0; j < p/2; ++j) {
	    ans += -v[j];
	    ans += v[p - 1 - j];
	  }
	}
	v.clear();
      }
    }
  }

  cout << ans << endl;
}


#include <iostream>
#include <vector>
using namespace std;

int main() {
  int n;
  cin >> n;
  int arr[n];
  int sum = 0;
  for (int i = 0; i < n; ++i) {
    cin >> arr[i];
    sum += arr[i];
  }
  if (sum == 1) {
    cout << -1 << endl;
    return 0;
  }
  long long min_ans = 10000000000000;
  for (int p = 2; p <= sum; ++p) {
    if (sum % p == 0) {
      while (sum % p == 0) {
	sum /= p;
      }
      vector<int> v;
      long long ans = 0;
      for (int i = 0; i < n; ++i) {
	if (arr[i] == 1) {
	  v.push_back(i);
	  if (v.size() == p) {
	    if (p == 2) {
	      ans += v[1] - v[0];
	    } else {
	      for (int j = 0; j < p/2; ++j) {
		ans += -v[j];
		ans += v[p - 1 - j];
	      }
	    }
	    v.clear();
	  }
	}
      }
      min_ans = min(min_ans, ans);
    }
  }
  cout << min_ans << endl;
}


#include <iostream>
#include <vector>
using namespace std;

int main() {
  int n;
  cin >> n;
  int arr[n];
  int sum = 0;
  for (int i = 0; i < n; ++i) {
    cin >> arr[i];
    sum += arr[i];
  }
  if (sum == 1) {
    cout << -1;
    return 0;
  }
  long long min_ans = 1000000000;
  for (int p = 2; p <= sum; ++p) {
    if (sum % p == 0) {
      while (sum % p == 0) {
	sum /= p;
      }

  vector<int> v;
  long long ans = 0;
  for (int i = 0; i < n; ++i) {
    if (arr[i] == 1) {
      v.push_back(i);
      if (v.size() == p) {
	if (p == 2) {
	  ans += v[1] - v[0];
	} else {
	  for (int j = 0; j < p/2; ++j) {
	    ans += -v[j];
	    ans += v[p - 1 - j];
	  }
	}
	v.clear();
      }
    }
  }

  min_ans = min(min_ans, ans);
    }}

  cout << min_ans << endl;
}


//CLOCKS_PER_SEC
using namespace std;
#include<bits/stdc++.h>
#define sqr(x) (x)*(x)
//#define sort stable_sort
#define ll long long
#define mk make_pair
#define pb push_back
#define in insert
#define mtr(x,y,z) mk(mk(x,y),z)
#define fi first
#define se second
#define lch(x) ((x)<<1)
#define rch(x) (((x)<<1)|1)
#define all(x) (x).begin(),(x).end()
#define titose CLOCKS_PER_SEC
#define fpi(x) freopen(x,"r",stdin);
#define fpo(x) freopen(x,"w",stdout);
#define fprio fpi("in.txt");fpo("out.txt");
#define fast ios_base::sync_with_stdio(false);
inline void read(int &x){int v=0,f=1;char c=getchar();while (!isdigit(c)&&c!='-') c=getchar();if (c=='-') f=-1; else v=(c&15);while (isdigit(c=getchar())) v=(v<<1)+(v<<3)+(c&15);x=v*f;}
inline void read(ll &x){ll v=0ll,f=1ll;char c=getchar();while (!isdigit(c)&&c!='-') c=getchar();if (c=='-') f=-1; else v=(c&15);while (isdigit(c=getchar())) v=(v<<1)+(v<<3)+(c&15);x=v*f;}
inline void readc(char &x){char c;while (((c=getchar())==' ')||c=='\n');x=c;}
inline void writes(string s){puts(s.c_str());}
inline void writeln(){writes("");}
inline void writei(int x){if (x<0){putchar('-');x=abs(x);}if (!x) putchar('0');char a[25];int top=0;while (x){a[++top]=(x%10)+'0';x/=10;}while (top){putchar(a[top]);top--;}}
inline void writell(ll x){if (x<0){putchar('-');x=abs(x);}if (!x) putchar('0');char a[25];int top=0;while (x){a[++top]=(x%10)+'0';x/=10;}while (top){putchar(a[top]);top--;}}
#define pii pair<int,int>
#define pll pair<ll,ll>
#define vi vector<int>
#define vl vector<ll>
#define si set<int>
#define sl set<ll>
#define mii map<int,int>
#define mll map<ll,ll>
#define msi map<string,int>
#define msl map<string,ll>
#define piii pair<int,pii >
#define piipi pair<pii,int>
#define plll pair<ll,pll >
#define pllpl pair<pll,ll>
#define pqi priority_queue<int>
#define pql priority_queue<ll>
#define npqi priority_queue<int,vector<int>,greater<int> >
#define npql priority_queue<ll,vector<ll>,greater<ll> >
#define forup(i,a,b) for ((i)=(a);(i)<=(b);(i)++)
#define fordo(i,a,b) for ((i)=(a);(i)>=(b);(i)--)
#define rep(i,x) forup ((i),1,(x))
#define repd(i,x) fordo ((i),(x),1)
#define itr iterator
#define fe(itcalc,c) for(__typeof((c).begin()) itcalc=(c).begin();itcalc!=(c).end();itcalc++)
#define NO {cout<<"NO";return 0;}
#define YES {cout<<"YES";return 0;}
#define y0 y000000000000000000000000000
#define y1 y111111111111111111111111111
#define j0 j000000000000000000000000000
#define j1 j111111111111111111111111111
#define cl0(a) memset((a),(0),(sizeof((a))))
#define clz(a) memset((a),(0x16),(sizeof((a))))
#define clf(a) memset((a),(-(0x16)),(sizeof((a))))
#define inf 0x3bbbbbbb
#define lnf 0x1bbbbbbbbbbbbbbbll
#define sqrt divi
#define p2(i) (1ll<<(i))
#define readi read
#define readll read
/*************************************************/
ll n,m,i,j,a[1000005],b[1000005],_=lnf,sum;
void solve(ll x)
{
	ll ans=0,mid,tmp,i;
	rep(i,n){
		b[i]=a[i]%x;
	}
	tmp=0;mid=-1;
	rep(i,n){
		if(mid==-1&&tmp+b[i]>=(x+1)/2){
			mid=i;ans+=tmp*i;ans-=(x-tmp)*i;
		}
		ll t=min(b[i],x-tmp);
		tmp+=t;b[i]-=t;
		if(mid==-1) ans-=t*i; else ans+=t*i;
		if(tmp==x){
			tmp=0;mid=-1;i--;
		}
	}
	_=min(ans,_);
}
int main()
{
	read(n);
	rep(i,n){
		read(a[i]);
		sum+=a[i];
	}
	if(sum==1)
	{
		puts("-1");
		return 0;
	}
	ll t=2;
	while(sum>=t*t){
		if(sum%t==0){
			solve(t);
			while(sum%t==0) sum/=t;
		}
		t++;
	}
	if(sum>1) solve(sum);
	cout<<_<<endl;
	return 0;
}


//CLOCKS_PER_SEC
using namespace std;
#include<bits/stdc++.h>
#define sqr(x) (x)*(x)
//#define sort stable_sort
#define ll long long
#define mk make_pair
#define pb push_back
#define in insert
#define mtr(x,y,z) mk(mk(x,y),z)
#define fi first
#define se second
#define lch(x) ((x)<<1)
#define rch(x) (((x)<<1)|1)
#define all(x) (x).begin(),(x).end()
#define titose CLOCKS_PER_SEC
#define fpi(x) freopen(x,"r",stdin);
#define fpo(x) freopen(x,"w",stdout);
#define fprio fpi("in.txt");fpo("out.txt");
#define fast ios_base::sync_with_stdio(false);
inline void read(int &x){int v=0,f=1;char c=getchar();while (!isdigit(c)&&c!='-') c=getchar();if (c=='-') f=-1; else v=(c&15);while (isdigit(c=getchar())) v=(v<<1)+(v<<3)+(c&15);x=v*f;}
inline void read(ll &x){ll v=0ll,f=1ll;char c=getchar();while (!isdigit(c)&&c!='-') c=getchar();if (c=='-') f=-1; else v=(c&15);while (isdigit(c=getchar())) v=(v<<1)+(v<<3)+(c&15);x=v*f;}
inline void readc(char &x){char c;while (((c=getchar())==' ')||c=='\n');x=c;}
inline void writes(string s){puts(s.c_str());}
inline void writeln(){writes("");}
inline void writei(int x){if (x<0){putchar('-');x=abs(x);}if (!x) putchar('0');char a[25];int top=0;while (x){a[++top]=(x%10)+'0';x/=10;}while (top){putchar(a[top]);top--;}}
inline void writell(ll x){if (x<0){putchar('-');x=abs(x);}if (!x) putchar('0');char a[25];int top=0;while (x){a[++top]=(x%10)+'0';x/=10;}while (top){putchar(a[top]);top--;}}
#define pii pair<int,int>
#define pll pair<ll,ll>
#define vi vector<int>
#define vl vector<ll>
#define si set<int>
#define sl set<ll>
#define mii map<int,int>
#define mll map<ll,ll>
#define msi map<string,int>
#define msl map<string,ll>
#define piii pair<int,pii >
#define piipi pair<pii,int>
#define plll pair<ll,pll >
#define pllpl pair<pll,ll>
#define pqi priority_queue<int>
#define pql priority_queue<ll>
#define npqi priority_queue<int,vector<int>,greater<int> >
#define npql priority_queue<ll,vector<ll>,greater<ll> >
#define forup(i,a,b) for ((i)=(a);(i)<=(b);(i)++)
#define fordo(i,a,b) for ((i)=(a);(i)>=(b);(i)--)
#define rep(i,x) forup ((i),1,(x))
#define repd(i,x) fordo ((i),(x),1)
#define itr iterator
#define fe(itcalc,c) for(__typeof((c).begin()) itcalc=(c).begin();itcalc!=(c).end();itcalc++)
#define NO {cout<<"NO";return 0;}
#define YES {cout<<"YES";return 0;}
#define y0 y000000000000000000000000000
#define y1 y111111111111111111111111111
#define j0 j000000000000000000000000000
#define j1 j111111111111111111111111111
#define cl0(a) memset((a),(0),(sizeof((a))))
#define clz(a) memset((a),(0x16),(sizeof((a))))
#define clf(a) memset((a),(-(0x16)),(sizeof((a))))
#define inf 0x3bbbbbbb
#define lnf 0x1bbbbbbbbbbbbbbbll
#define sqrt divi
#define p2(i) (1ll<<(i))
#define readi read
#define readll read
/*************************************************/
ll n,m,i,j,a[1000005],b[1000005],_=lnf,sum;
void solve(ll x)
{
	ll ans=0,mid,tmp,i;
	rep(i,n){
		b[i]=a[i]%x;
	}
	tmp=0;mid=-1;
	rep(i,n){
		if(mid==-1&&tmp+b[i]>=(x+1)/2){
			mid=i;ans+=tmp*i;ans-=(x-tmp)*i;
		}
		ll t=min(b[i],x-tmp);
		tmp+=t;b[i]-=t;
		if(mid==-1) ans-=t*i; else ans+=t*i;
		if(tmp==x){
			tmp=0;mid=-1;i--;
		}
	}
	_=min(ans,_);
}
int main()
{
	read(n);
	rep(i,n){
		read(a[i]);
		sum+=a[i];
	}
	if(sum==1)
	{
		puts("-1");
		return 0;
	}
	ll t=2;
	while(sum>=t*t){
		if(sum%t==0){
			solve(t);
			while(sum%t==0) sum/=t;
		}
		t++;
	}
	if(sum) solve(sum);
	cout<<_<<endl;
	return 0;
}


#include <bits/stdc++.h>
#define pb push_back
using namespace std;

inline int read()
{
	int sum=0,ff=1; char ch=getchar();
	while(!isdigit(ch))
	{
		if(ch=='-') ff=-1;
		ch=getchar();
	}
	while(isdigit(ch))
		sum=sum*10+(ch^48),ch=getchar();
	return sum*ff;
}

const int N=1e5+5;

int n,m,a[N],sum,ans=1e9;

inline int solve(int x)
{
	int all=0,gs=0;
	for ( int i=1;i<=n;i++ )
	{
		all=(all+a[i])%x;
		gs+=min(all,x-all);
	}
	return gs;
}

int main()
{
	n=read();
	for ( int i=1;i<=n;i++ )
	{
		a[i]=read();
		sum+=a[i];
	}
	if(!sum) return 0;
	for ( int i=2;i*i<=sum;i++ )
		if(sum%i==0)
		{
			ans=min(ans,solve(i));
			while(sum%i==0)
				sum/=i;
		}
	if(sum>1) ans=min(ans,solve(sum));
	if(ans==1e9) return printf("-1\n"),0;
	printf("%d\n",ans);
	return 0;
}


#include <bits/stdc++.h>
#define int long long
#define pb push_back
using namespace std;

inline int read()
{
	int sum=0,ff=1; char ch=getchar();
	while(!isdigit(ch))
	{
		if(ch=='-') ff=-1;
		ch=getchar();
	}
	while(isdigit(ch))
		sum=sum*10+(ch^48),ch=getchar();
	return sum*ff;
}

const int N=1e6+5;

int n,m,a[N],sum,ans=1e18;

inline int solve(int x)
{
	int all=0,gs=0;
	for ( int i=1;i<=n;i++ )
	{
		all=(all+a[i])%x;
		gs+=min(all,x-all);
	}
	return gs;
}

signed main()
{
	n=read();
	for ( int i=1;i<=n;i++ )
	{
		a[i]=read();
		sum+=a[i];
	}
	if(sum<2) return printf("-1\n"),0;
	for ( int i=2;i*i<=sum;i++ )
		if(sum%i==0)
		{
			ans=min(ans,solve(i));
			while(sum%i==0)
				sum/=i;
		}
	if(sum>1) ans=min(ans,solve(sum));
	if(ans==1e18) return printf("-1\n"),0;
	printf("%lld\n",ans);
	return 0;
}


#include<bits/stdc++.h>
#define ll long long
using namespace std;
int n,a[100010],p[100010],sum=0;ll lsum[100010];
ll sol(int e,int len,ll pos,int t){
    ll bef=pos*(t-1-e+len)-(lsum[t-1]-lsum[e-len]);
    ll aft=(lsum[e]-lsum[t-1])-pos*(e-t+1);
    //cout<<bef<<' '<<aft<<endl;
    return aft+bef;
}
int main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
        if(a[i])p[++sum]=i;
    }
    for(int i=1;i<=sum;i++){
        lsum[i]=lsum[i-1]+p[i];
    }
    for(int i=2;i<=sum;i++){
        if(sum%i)continue;
        if(sum/i>n){
            printf("-1\n");return 0;
        }
        ll tmp=0,ans=0;
        for(int j=i;j<=sum;j+=i){
            int pos=(p[j]+p[j-i+1])/2;
            int t1=lower_bound(p+j-i+1,p+j,pos)-p;
            int t2=lower_bound(p+j-i+1,p+j,pos+1)-p;
            //cout<<p[j]<<' '<<pos<<' '<<t<<endl;
            ans+=min(sol(j,i,pos,t1),sol(j,i,pos+1,t2));
            //cout<<sol(j,i,pos,t)<<endl;
        }
        cout<<ans<<endl;
        return 0;
    }
    cout<<"-1"<<endl;
}
/*
10
1 1 1 1 1 0 0 0 0 0
*/


#include<bits/stdc++.h>
#define ll long long
using namespace std;
int n,a[100010],p[100010],sum=0;ll lsum[100010];
ll sol(int e,int len,ll pos,int t){
    ll bef=pos*(t-1-e+len)-(lsum[t-1]-lsum[e-len]);
    ll aft=(lsum[e]-lsum[t-1])-pos*(e-t+1);
    //cout<<bef<<' '<<aft<<endl;
    return aft+bef;
}
int main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
        if(a[i])p[++sum]=i;
    }
    for(int i=1;i<=sum;i++){
        lsum[i]=lsum[i-1]+p[i];
    }
    for(int i=2;i<=sum;i++){
        if(sum%i)continue;
        if(sum/i>n){
            printf("-1\n");return 0;
        }
        ll tmp=0,ans=0;
        for(int j=i;j<=sum;j+=i){
            int pos=(p[j]+p[j-i+1])/2;
            int t=lower_bound(p+j-i+1,p+j,pos)-p;
            //cout<<p[j]<<' '<<pos<<' '<<t<<endl;
            ans+=sol(j,i,pos,t);
            //cout<<sol(j,i,pos,t)<<endl;
        }
        cout<<ans<<endl;
        return 0;
    }
    cout<<"-1"<<endl;
}
/*
10
1 1 1 1 1 0 0 0 0 0
*/


#include<bits/stdc++.h>
#define ll long long
using namespace std;
int n,a[100010],p[100010],sum=0;ll lsum[100010];
ll sol(int e,int len,ll pos,int t){
    ll bef=pos*(t-1-e+len)-(lsum[t-1]-lsum[e-len]);
    ll aft=(lsum[e]-lsum[t-1])-pos*(e-t+1);
    //cout<<bef<<' '<<aft<<endl;
    return aft+bef;
}
int main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
        if(a[i])p[++sum]=i;
    }
    for(int i=1;i<=sum;i++){
        lsum[i]=lsum[i-1]+p[i];
    }
    ll ans=1e18+10;
    for(int i=2;i<=sum;i++){
        if(sum%i)continue;
        if(sum/i>n){
            printf("-1\n");return 0;
        }
        ll tmp=0;
        for(int j=i;j<=sum;j+=i){
            int pos=p[j-i/2];
            //int t1=lower_bound(p+j-i+1,p+j,pos)-p;
            //int t2=lower_bound(p+j-i+1,p+j,pos+1)-p;
            //cout<<p[j]<<' '<<pos<<' '<<t<<endl;
            tmp+=sol(j,i,pos,j-i/2);
            //cout<<sol(j,i,pos,t)<<endl;
        }
        ans=min(ans,tmp);
    }
    if(ans==1e18+10)cout<<"-1"<<endl;
    else cout<<ans<<endl;
}
/*
10
1 1 1 1 1 0 0 0 0 0
*/


#include<bits/stdc++.h>
#define ll long long
using namespace std;
int n,a[100010];
int main(){
    cin>>n;
    int sum=0;
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
        sum+=a[i];
    }
    ll ans=0;
    for(int i=2;i<=sum;i++){
        if(sum%i)continue;
        if(sum/i>n){
            printf("-1\n");return 0;
        }
        int cnt=0,pos=0;
        ll tmp=0;
        for(int j=1;j<=n;j++){
            if(!a[j])continue;
            if(!pos)pos=j;
            cnt++;
            tmp+=j-pos;
            if(cnt==i){
                ans+=min(tmp,(ll)i*(j-pos)-tmp);//cout<<tmp<<endl;
                pos=j;tmp=0;
            }
        }
        cout<<ans<<endl;
        return 0;
    }
    cout<<"-1"<<endl;
}
/*
10
1 1 1 1 1 0 0 0 0 0
*/


#include<bits/stdc++.h>
#define ll long long
using namespace std;
int n,a[100010],p[100010],sum=0;ll lsum[100010];
ll sol(int e,int len,ll pos,int t){
    ll bef=pos*(t-1-e+len)-(lsum[t-1]-lsum[e-len]);
    ll aft=(lsum[e]-lsum[t-1])-pos*(e-t+1);
    //cout<<bef<<' '<<aft<<endl;
    return aft+bef;
}
int main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
        if(a[i])p[++sum]=i;
    }
    for(int i=1;i<=sum;i++){
        lsum[i]=lsum[i-1]+p[i];
    }
    for(int i=2;i<=sum;i++){
        if(sum%i)continue;
        if(sum/i>n){
            printf("-1\n");return 0;
        }
        ll tmp=0,ans=0;
        for(int j=i;j<=sum;j+=i){
            int pos=p[j-i/2];
            //int t1=lower_bound(p+j-i+1,p+j,pos)-p;
            //int t2=lower_bound(p+j-i+1,p+j,pos+1)-p;
            //cout<<p[j]<<' '<<pos<<' '<<t<<endl;
            ans+=sol(j,i,pos,j-i/2);
            //cout<<sol(j,i,pos,t)<<endl;
        }
        cout<<ans<<endl;
        return 0;
    }
    cout<<"-1"<<endl;
}
/*
10
1 1 1 1 1 0 0 0 0 0
*/


#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e6,inf=1e9;
int aa[N+2],bb[N+2];
bool isPrime(int x)
{
  for(int i=2;i<x;i++)
    if(x%i==0)return 0;
  return 1;
}
int main()
{
  ios_base::sync_with_stdio(0);cin.tie(0);
  int n;cin>>n;int sm=0;
  for(int i=1;i<=n;i++)cin>>aa[i],sm+=aa[i];
  for(int i=1;i<=n;i++)bb[i]=aa[i];
  if(sm==1)cout<<-1<<endl,exit(0);

  int ans=inf;
  for(int p=2;p<=sm;p++)
  {
    if(sm%p||(!isPrime(p)))continue;
    int now=0;
    for(int i=1;i<=n;i++)aa[i]=bb[i];
    for(int i=1;i<=n;i++)
    {
      if(aa[i]<0)
      {
        now-=aa[i];aa[i+1]-=aa[i];
      }
      else
      {
        int ex=aa[i]%p;
        if(ex<p-ex)now+=ex,aa[i+1]+=ex;
        else now+=p-ex,aa[i-1]-=(p-ex);
      }
    }
    ans=min(ans,now);
  }
  cout<<ans<<endl;
  return 0;
}


#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e6,inf=1e9;
int aa[N+2],bb[N+2];
bool isPrime(int x)
{
  for(int i=2;i<x;i++)
    if(x%i==0)return 0;
  return 1;
}
int main()
{
  ios_base::sync_with_stdio(0);cin.tie(0);
  int n;cin>>n;int sm=0;
  for(int i=1;i<=n;i++)cin>>aa[i],sm+=aa[i];
  for(int i=1;i<=n;i++)bb[i]=aa[i];

  int ans=inf;
  for(int p=2;p<=sm;p++)
  {
    if(sm%p||(!isPrime(p)))continue;
    //cout<<"*"<<p<<endl;
    int now=0;
    for(int i=1;i<=n;i++)aa[i]=bb[i];
    for(int i=1;i<=n;i++)
    {
      if(aa[i]<0)
      {
        now-=aa[i];aa[i+1]+=aa[i];
      }
      else
      {
        int ex=aa[i]%p;
        if(ex<p-ex)now+=ex,aa[i+1]+=ex;
        else now+=p-ex,aa[i+1]-=(p-ex);
      }
    }
    ans=min(ans,now);
  }
  if(ans==inf)ans=-1;
  cout<<ans<<endl;
  return 0;
}


#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e6,inf=1e9;
int aa[N+2],bb[N+2];
bool isPrime(int x)
{
  for(int i=2;i<x;i++)
    if(x%i==0)return 0;
  return 1;
}
int main()
{
  ios_base::sync_with_stdio(0);cin.tie(0);
  int n;cin>>n;int sm=0;
  for(int i=1;i<=n;i++)cin>>aa[i],sm+=aa[i];
  for(int i=1;i<=n;i++)bb[i]=aa[i];

  int ans=inf;
  for(int p=2;p<=sm;p++)
  {
    if(sm%p||(!isPrime(p)))continue;
    //cout<<"*"<<p<<endl;
    int now=0;
    for(int i=1;i<=n;i++)aa[i]=bb[i];
    for(int i=1;i<=n;i++)
    {
      if(aa[i]<0)
      {
        now-=aa[i];aa[i+1]+=aa[i];
      }
      else
      {
        int ex=aa[i]%p;
        if(ex<p-ex)now+=ex,aa[i+1]+=ex;
        else now+=p-ex,aa[i-1]-=(p-ex);
      }
    }
    ans=min(ans,now);
  }
  if(ans==inf)ans=-1;
  cout<<ans<<endl;
  return 0;
}


#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e6;
const long inf=1e18;
int aa[N+2],bb[N+2];
bool isPrime(int x)
{
  for(int i=2;i<x;i++)
    if(x%i==0)return 0;
  return 1;
}
int main()
{
  ios_base::sync_with_stdio(0);cin.tie(0);
  int n;cin>>n;int sm=0;
  for(int i=1;i<=n;i++)cin>>aa[i],sm+=aa[i];
  for(int i=1;i<=n;i++)bb[i]=aa[i];

  long ans=inf;
  for(int p=2;p<=sm;p++)
  {
    if(sm%p||(!isPrime(p)))continue;
    //cout<<"*"<<p<<endl;
    long now=0;
    for(int i=1;i<=n;i++)aa[i]=bb[i];
    for(int i=1;i<=n;i++)
    {
      if(aa[i]<0)
      {
        now-=aa[i];aa[i+1]+=aa[i];
      }
      else
      {
        int ex=aa[i]%p;
        if(ex<p-ex)now+=ex,aa[i+1]+=ex;
        else now+=p-ex,aa[i+1]-=(p-ex);
      }
    }
    ans=min(ans,now);
  }
  if(ans==inf)ans=-1;
  cout<<ans<<endl;
  return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef long double ld;

const ll INF = 1e18;
const int MOD = 1000000007;
const ld EPS = 1e-9;
const ld PI = acos(-1);

#define x first
#define y second

int N, A[100010];

struct Sieve {
    vector<bool> isPrime;
    vector<int> primes;
    Sieve(int lim) {
        isPrime.assign(lim, true);
        isPrime[0] = isPrime[1] = false;
        for (int i=2; i*i < lim; i++)
            if (isPrime[i]) {
                primes.push_back(i);
                for (int j = i*i; j < lim; j+=i)
                    isPrime[j] = false;
            }
    }
};

int sum = 0;

long long countMoves(int p) {
    int pos = -1;
    long long res = 0;
    for (int i = 0; i < sum / p; i++) {
        vector<int> val;
        while (pos + 1 < N && val.size() < p) {
            pos++;
            if (A[pos]) val.push_back(pos);
        }
        if (val.size() == 2)
            res += val[1] - val[0];
        else {
            int med = val[val.size() / 2];
            for (int j : val)
                res += abs(j - med);
        }
    }
    return res;
}

int main() {
    ios_base::sync_with_stdio(false); cin.tie(0);
    cout << fixed << setprecision(10);

    Sieve sieve(1000000);

    cin >> N;
    for (int i = 0; i < N; i++) cin >> A[i];

    for (int i = 0; i < N; i++) sum += A[i];

    auto& primes = sieve.primes;
    long long ans = INF;
    for (int i = 0; i < primes.size() && primes[i] <= sum; i++) {
        if (sum % primes[i] == 0) {
            ans = min(ans, countMoves(primes[i]));
        }
    }

    if (ans == INF) ans = -1;
    cout << ans << "\n";

    return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef long double ld;

const ll INF = 1e18;
const int MOD = 1000000007;
const ld EPS = 1e-9;
const ld PI = acos(-1);

#define x first
#define y second

int N, A[100010];

struct Sieve {
    vector<bool> isPrime;
    vector<int> primes;
    Sieve(int lim) {
        isPrime.assign(lim, true);
        isPrime[0] = isPrime[1] = false;
        for (int i=2; i*i < lim; i++)
            if (isPrime[i]) {
                primes.push_back(i);
                for (int j = i*i; j < lim; j+=i)
                    isPrime[j] = false;
            }
    }
};

int sum = 0;

long long countMoves(int p) {
    int pos = -1;
    long long res = 0;
    for (int i = 0; i < sum / p; i++) {
        vector<int> val;
        while (pos + 1 < N && val.size() < p) {
            pos++;
            if (A[pos]) val.push_back(pos);
        }
        if (val.size() == 2)
            res += val[1] - val[0];
        else {
            int med = val[val.size() / 2];
            for (int j : val)
                res += abs(j - med);
        }
    }
    return res;
}

int main() {
    ios_base::sync_with_stdio(false); cin.tie(0);
    cout << fixed << setprecision(10);

    Sieve sieve(1000000);

    cin >> N;
    for (int i = 0; i < N; i++) cin >> A[i];

    for (int i = 0; i < N; i++) sum += A[i];

    auto& primes = sieve.primes;
    long long ans = -1;
    for (int i = 0; i < primes.size() && primes[i] <= sum; i++) {
        if (sum % primes[i] == 0) {
            ans = countMoves(primes[i]);
            break;
        }
    }

    cout << ans << "\n";

    return 0;
}


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef long double ld;

const ll INF = 1e18;
const int MOD = 1000000007;
const ld EPS = 1e-9;
const ld PI = acos(-1);

#define x first
#define y second

int N, A[100010];

struct Sieve {
    vector<bool> isPrime;
    vector<int> primes;
    Sieve(int lim) {
        isPrime.assign(lim, true);
        isPrime[0] = isPrime[1] = false;
        for (int i=2; i < lim; i++)
            if (isPrime[i]) {
                primes.push_back(i);
                for (ll j = (ll) i*i; j < lim; j+=i)
                    isPrime[j] = false;
            }
    }
};

int sum = 0;

long long countMoves(int p) {
    int pos = -1;
    long long res = 0;
    for (int i = 0; i < sum / p; i++) {
        vector<int> val;
        while (pos + 1 < N && val.size() < p) {
            pos++;
            if (A[pos]) val.push_back(pos);
        }
        int med = val[val.size() / 2];
        for (int j : val)
            res += abs(j - med);
    }
    return res;
}

int main() {
    ios_base::sync_with_stdio(false); cin.tie(0);
    cout << fixed << setprecision(10);

    Sieve sieve(1000000);

    cin >> N;
    for (int i = 0; i < N; i++) cin >> A[i];

    for (int i = 0; i < N; i++) sum += A[i];

    auto& primes = sieve.primes;
    long long ans = INF;
    for (int i = 0; i < primes.size() && primes[i] <= sum; i++) {
        if (sum % primes[i] == 0) {
            ans = min(ans, countMoves(primes[i]));
        }
    }

    if (ans == INF) ans = -1;
    cout << ans << "\n";

    return 0;
}


#include <bits/stdc++.h>
#define rep(i,a,b) for(int i = (a); i <= (b); ++ i)
#define per(i,a,b) for(int i = (a); i >= (b); -- i)
#define pb push_back
#define VI vector<int>
#define VVI vector<VI>
#define Pii pair<int,int>
#define Pll pair<ll,ll>
#define Pli pair<ll,int>
#define fi first
#define se second
#define Ppi pair<Pii,int>
#define VII vector<Pii>

using namespace std;

typedef long long ll;
typedef int (*funI_I) (int);
typedef int (*funI_II) (int, int);

constexpr int N = 4000100;

int n, sum = 0, a[N];
VII A;

int main() {
    ios::sync_with_stdio(false); cin.tie(0);

    cin >> n;
    rep(i, 1, n) cin >> a[i], sum += a[i];
    if(sum == 1) {
        cout << -1 << "\n";
        return 0;
    }
    auto cal = [&](int l, int r) {
        // cout << l << " " << r << endl;
        int ans = 0;
        VI A;
        rep(i, l, r) if(a[i]) A.pb(i);
        // cout << A.size() << endl;

        auto cal_ = [&](int p) {
            // cout << p << endl;
            int res = 0;
            for(int vv: A) res += abs(vv-p);
            return res;
        };

        int bz = A.size() - 1;
        if(A.size() & 1) {
            ans = cal_(A[bz/2]);
        } else {
            ans = min(cal_(A[bz/2]), cal_(A[bz/2+1]));
        }
        return ans;
    };
    int B;
    for(B = 2; B <= sum; ++ B) if(sum % B == 0) break;
    int ans = 0;
    for(int i = 1; i <= n ;) {
        int tmp = 0, st = i;
        while(i <= n && tmp < B) tmp += a[i++];
        ans += cal(st,i-1);
    }
    cout << ans << "\n";
}


#include <bits/stdc++.h>
#define rep(i,a,b) for(int i = (a); i <= (b); ++ i)
#define per(i,a,b) for(int i = (a); i >= (b); -- i)
#define pb push_back
#define VI vector<int>
#define VVI vector<VI>
#define Pii pair<int,int>
#define Pll pair<ll,ll>
#define Pli pair<ll,int>
#define fi first
#define se second
#define Ppi pair<Pii,int>
#define VII vector<Pii>

using namespace std;

typedef long long ll;
typedef int (*funI_I) (int);
typedef int (*funI_II) (int, int);

constexpr int N = 4000100;

int n, sum = 0, a[N];
VII A;

int main() {
    ios::sync_with_stdio(false); cin.tie(0);
    cin >> n;
    rep(i, 1, n) cin >> a[i], sum += a[i];
    if(sum == 1) {
        cout << -1 << "\n";
        return 0;
    }
    auto cal = [&](int l, int r) {
        ll ans = 0;
        VI A;
        rep(i, l, r) if(a[i]) A.pb(i);
        auto cal_ = [&](int p) {
            ll res = 0;
            for(int vv: A) res += abs(vv-p);
            return res;
        };
        int bz = A.size() - 1;
        if(A.size() & 1) {
            ans = cal_(A[bz/2]);
        } else {
            ans = min(cal_(A[bz/2]), cal_(A[bz/2+1]));
        }
        return ans;
    };
    int B;
    ll ans = 1e18;
    auto calans = [&](int B) {
        ll ans = 0;
        for(int ss = 0, i = 1; i <= n && ss < sum;) {
            int tmp = 0, st = i;
            while(i <= n && tmp < B) tmp += a[i++];
            ss += tmp;
            ans += cal(st,i-1);
        }
        return ans;
    };
    for(B = 2; B * B <= sum; ++ B) if(sum % B == 0) {
        ans = min(ans, calans(B));
        if(B*B == sum) continue;
        ans = min(ans, calans(sum/B));
        break;
    }
    ans = min(ans, calans(sum));
    cout << ans << "\n";
}


#include <bits/stdc++.h>
#define rep(i,a,b) for(int i = (a); i <= (b); ++ i)
#define per(i,a,b) for(int i = (a); i >= (b); -- i)
#define pb push_back
#define VI vector<int>
#define VVI vector<VI>
#define Pii pair<int,int>
#define Pll pair<ll,ll>
#define Pli pair<ll,int>
#define fi first
#define se second
#define Ppi pair<Pii,int>
#define VII vector<Pii>

using namespace std;

typedef long long ll;
typedef int (*funI_I) (int);
typedef int (*funI_II) (int, int);

constexpr int N = 4000100;

int n, sum = 0, a[N];
VII A;

int main() {
    ios::sync_with_stdio(false); cin.tie(0);

    cin >> n;
    rep(i, 1, n) cin >> a[i], sum += a[i];
    if(sum == 1) {
        cout << -1 << "\n";
        return 0;
    }
    auto cal = [&](int l, int r) {
        // cout << l << " " << r << endl;
        ll ans = 0;
        VI A;
        rep(i, l, r) if(a[i]) A.pb(i);
        // cout << A.size() << endl;

        auto cal_ = [&](int p) {
            // cout << p << endl;
            ll res = 0;
            for(int vv: A) res += abs(vv-p);
            return res;
        };

        int bz = A.size() - 1;
        if(A.size() & 1) {
            ans = cal_(A[bz/2]);
        } else {
            ans = min(cal_(A[bz/2]), cal_(A[bz/2+1]));
        }
        return ans;
    };
    int B;
    ll ans = 1e18;

    auto calans = [&](int B) {
        ll ans = 0;
        for(int ss = 0, i = 1; i <= n && ss < sum;) {
            int tmp = 0, st = i;
            while(i <= n && tmp < B) tmp += a[i++];
            ss += tmp;
            ans += cal(st,i-1);
        }
        return ans;
    };

    for(B = 2; B * B <= sum; ++ B) if(sum % B == 0) {
        ans = min(ans, calans(B));
        if(B*B == sum) continue;
        ans = min(ans, calans(sum/B));
    }
    ans = min(ans, calans(sum));
    cout << ans << "\n";
}


#include <bits/stdc++.h>
#define rep(i,a,b) for(int i = (a); i <= (b); ++ i)
#define per(i,a,b) for(int i = (a); i >= (b); -- i)
#define pb push_back
#define VI vector<int>
#define VVI vector<VI>
#define Pii pair<int,int>
#define Pll pair<ll,ll>
#define Pli pair<ll,int>
#define fi first
#define se second
#define Ppi pair<Pii,int>
#define VII vector<Pii>

using namespace std;

typedef long long ll;
typedef int (*funI_I) (int);
typedef int (*funI_II) (int, int);

constexpr int N = 4000100;

int n, sum = 0, a[N];
VII A;

int main() {
    ios::sync_with_stdio(false); cin.tie(0);

    cin >> n;
    rep(i, 1, n) cin >> a[i], sum += a[i];
    if(sum == 1) {
        cout << -1 << "\n";
        return 0;
    }
    auto cal = [&](int l, int r) {
        // cout << l << " " << r << endl;
        int ans = 0;
        VI A;
        rep(i, l, r) if(a[i]) A.pb(i);
        // cout << A.size() << endl;

        auto cal_ = [&](int p) {
            // cout << p << endl;
            int res = 0;
            for(int vv: A) res += abs(vv-p);
            return res;
        };

        int bz = A.size() - 1;
        if(A.size() & 1) {
            ans = cal_(A[bz/2]);
        } else {
            ans = min(cal_(A[bz/2]), cal_(A[bz/2+1]));
        }
        return ans;
    };
    int B;
    ll ans = 1e18;

    auto calans = [&](int B) {
        ll ans = 0;
        for(int ss = 0, i = 1; i <= n && ss < sum;) {
            int tmp = 0, st = i;
            while(i <= n && tmp < B) tmp += a[i++];
            ss += tmp;
            ans += cal(st,i-1);
        }
        return ans;
    };

    for(B = 2; B * B <= sum; ++ B) if(sum % B == 0) {
        ans = min(ans, calans(B));
        if(B*B == sum) continue;
        ans = min(ans, calans(sum/B));
    }
    ans = min(ans, calans(sum));
    cout << ans << "\n";
}


#include <cstdio>
#include <vector>
using namespace std;
const int MAXN=110000;
const int INF=1E9;
int n, s, a[MAXN];
int getdis(vector<int>& v)
{
	int d=0;
	for (int i=1; i<=v.size()/2; i++)
		d+=i*v[i-1];
	for (int i=v.size()/2+1; i<=v.size(); i++)
		d+=((v.size()-i+1)*v[i-1]);
	return d;
}
int solve(int k)
{
	int res=0;
	vector<int> v;
	for (int i=1, t=0; i<=n; i++)
		if (a[i]==1)
		{
			if (t) v.push_back(i-t);
			if (v.size()==k-1)
				res+=getdis(v), v.clear(), t=0;
			else t=i;
		}
	return res;
}
int main()
{
//	freopen("B.in", "r", stdin);
//	freopen("B.out", "w", stdout);
	scanf("%d", &n); s=0;
	for (int i=1; i<=n; i++)
		scanf("%d", &a[i]), s+=a[i];
	int ans=INF;
	for (int k=1; k*k<=s; k++)
		if (s%k==0)
		{
			if (k!=1) ans=min(ans, solve(k));
			if (n/k!=1&&k*k!=s) ans=min(ans, solve(s/k));
		}
	printf("%d\n", ans==INF?-1:ans);
	return 0;
}


#include <cstdio>
#include <vector>
using namespace std;
typedef long long ll;
const int MAXN=110000;
const ll INF=1E18;
int n, s, a[MAXN];
ll getdis(vector<int>& v)
{
	ll d=0;
	for (int i=1; i<=v.size()/2; i++)
		d+=1ll*i*v[i-1];
	for (int i=v.size()/2+1; i<=v.size(); i++)
		d+=1ll*(v.size()-i+1)*v[i-1];
	return d;
}
ll solve(int k)
{
	ll res=0;
	vector<int> v;
	for (int i=1, t=0; i<=n; i++)
		if (a[i]==1)
		{
			if (t) v.push_back(i-t);
			if (v.size()==k-1)
				res+=getdis(v), v.clear(), t=0;
			else t=i;
		}
	return res;
}
int main()
{
//	freopen("B.in", "r", stdin);
//	freopen("B.out", "w", stdout);
	scanf("%d", &n); s=0;
	for (int i=1; i<=n; i++)
		scanf("%d", &a[i]), s+=a[i];
	ll ans=INF;
	for (int k=1; k*k<=s; k++)
		if (s%k==0)
		{
			if (k!=1) ans=min(ans, solve(k));
			if (n/k!=1&&k*k!=s) ans=min(ans, solve(s/k));
		}
	printf("%lld\n", ans==INF?-1:ans);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int maxn=1001000;
int n,a[maxn],ttt=0;
long long sum=0;
long long per=0;
long long ans=1e18;
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++) scanf("%d",a+i),sum+=a[i],ttt=__gcd(ttt,a[i]);
	if(sum==1) return puts("-1"),0;
	per=sum;
	for(long long i=2;i*i<=sum;i++) if(sum%i==0)
	{
		per=i;long long Sum=0,res=0;
		for(int j=1;j<=n;j++) Sum+=a[j],res+=min(Sum%per,per-Sum%per);
		ans=min(ans,res);
		while(sum%i==0) sum/=i;
	}
	per=sum;long long Sum=0,res=0;
	for(int j=1;j<=n;j++) Sum+=a[j],res+=min(Sum%per,per-Sum%per);
	ans=min(ans,res);
	printf("%lld\n",ans);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
const int maxn=1001000;
int n,a[maxn],ttt=0;
long long sum=0;
long long per=0;
long long ans=1e18;
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++) scanf("%d",a+i),sum+=a[i],ttt=__gcd(ttt,a[i]);
	if(sum==1) return puts("-1"),0;
	per=sum;
	for(long long i=2;i*i<=sum;i++) if(sum%i==0)
	{
		per=i;long long Sum=0,res=0;
		for(int j=1;j<=n;j++) Sum+=a[j],res+=min(Sum%per,per-Sum%per);
		ans=min(ans,res);
		while(sum%i==0) sum/=i;
	}
	per=sum;long long Sum=0,res=0;
	for(int j=1;j<=n;j++) Sum+=a[j],res+=min(Sum%per,per-Sum%per);
	if(sum!=1) ans=min(ans,res);
	printf("%lld\n",ans);
	return 0;
}


#include <bits/stdc++.h>

#define ll long long
#define N ((int)1e6+10)
#define MOD ((int)1e9+7)

using namespace std;

int r, c, k, t, n;
ll a[N], b[N];
ll sum = 0;

ll calc(int l, int r, int x, ll sum) {
    ll res = 0;
    for (int i = l; i <= r; i++) {
        ll val = min(sum, b[i]);
        sum -= val;
        res += val * abs(i - x);
    }
    return res;
}

ll search(int l, int r, ll sum) {

    int s = l, e = r;
    while (r - l >= 3) {
        int m1 = l + (r - l) / 3;
        int m2 = r - (r - l) / 3;
        ll f1 = calc(s, e, m1, sum);      //evaluates the function at m1
        ll f2 = calc(s, e, m2, sum);      //evaluates the function at m2
        if (f1 < f2)
            r = m2;
        else
            l = m1;
    }
    ll ans = calc(s,e,l,sum);
    for (int j = max(l, s); j <= min(e, r); j++) {
        ans = min(ans, calc(s, e, j, sum));
    }
    return ans;
}

ll try_this(ll d) {
    ll res = 0;
    int l = 0, r = -1;
    ll s = 0;
    for (int i = 0; i < n; i++) {
        b[i] = a[i];
    }
    for (int i = 0; i < n; i++) {
        if(s == 0){
            l = i;
        }
        s += a[i];
        r = i;
        if (s / d > 0) {
            ll ds = s - (s % d);
            res += search(l, r, ds);
            s = s % d;
            b[i] = s;
            l = i;
        }
    }
    return res;
}

int main() {

    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf("%lld", &a[i]);
        sum += a[i];
    }
    if (sum == 1) {
        printf("%d\n", -1);
        return 0;
    }

    vector<ll> f;
    ll s2 = sum;
    for (int i = 2; i * i <= sum; i++) {
        if (s2 % i == 0) {
            f.push_back(i);
        }
        while (s2 % i == 0) {
            s2 /= i;
        }
    }
    if (s2 > 1) {
        f.push_back(s2);
    }
    b[0] = a[0];
    for (int i = 1; i < n; i++) {
        b[i] += b[i - 1];
        b[i] += a[i];
    }
    ll ans = 1e18;
    for (int j = 0; j < f.size(); j++) {
        ans = min(ans, try_this(f[j]));
    }
    printf("%lld\n", ans);
    return 0;
}


#include <bits/stdc++.h>

#define ll long long
#define N ((int)2e6+10)
#define MOD ((int)1e9+7)

using namespace std;

int r, c, k, t, n;
ll a[N], b[N];
ll sum = 0;

ll calc(int l, int r, int x, ll sum) {
    ll res = 0;
    for (int i = l; i <= r; i++) {
        ll val = min(sum, b[i]);
        sum -= val;
        res += val * abs(i - x);
    }
    return res;
}

ll search(int l, int r, ll sum) {
    ll ans = 1e18;
    int s = l, e = r;
    while (r - l >= 3) {
        int m1 = l + (r - l) / 3;
        int m2 = r - (r - l) / 3;
        ll f1 = calc(s, e, m1, sum);      //evaluates the function at m1
        ll f2 = calc(s, e, m2, sum);      //evaluates the function at m2

        if (f1 == f2) {
            f1 = calc(s, e, l, sum);
            f2 = calc(s, e, r, sum);
        }
        if (f1 > f2)
            l = m1;
        else
            r = m2;
    }
    for (int j = max(l, s); j <= min(e, r); j++) {
        ans = min(ans, calc(s, e, j, sum));
    }
    return ans;
}

ll try_this(ll d) {
    ll res = 0;
    int l = 0, r = -1;
    ll s = 0;
    for (int i = 0; i < n; i++) {
        b[i] = a[i] % d;
    }
    for (int i = 0; i < n; i++) {
        if (s == 0) {
            l = i;
        }
        s += b[i];
        r = i;
        if (s / d > 0) {
            res += search(l, r, d);
            s = s - d;
            b[i] = s;
            l = i;
        }
    }
    return res;
}

int main() {
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf("%lld", &a[i]);
        sum += a[i];
    }
    if (sum == 1) {
        printf("%d\n", -1);
        return 0;
    }

    vector<ll> f;
    ll s2 = sum;
    for (ll i = 2; i <= 1e6 + 40; i++) {
        if (s2 % i == 0) {
            f.push_back(i);
        }
        while (s2 % i == 0) {
            s2 /= i;
        }
    }
    if (s2 > 1) {
        f.push_back(s2);
    }
    ll ans = 1e18;
    for (int j = 0; j < f.size(); j++) {
        ans = min(ans, try_this(f[j]));
    }
    printf("%lld\n", ans);
    return 0;
}


#include <bits/stdc++.h>

#define ll long long
#define N ((int)1e6+10)
#define MOD ((int)1e9+7)

using namespace std;

int r,c,k,t,n;
int a[200005];
ll sum = 0;
int main() {
    scanf("%d",&n);
    for(int i = 0 ; i < n;i++){
        scanf("%d",&a[i]);
        sum += a[i];
    }
    if(sum == 1){
        printf("%d\n",-1);
        return 0;
    }
    for(int i = 1 ; i < n;i++){
        a[i] += a[i-1];
    }
    ll ans = 1e18;
    for(int j = 2; j <= sum;j++){
        if(sum % j != 0)
            continue;

       ll res = 0;
       int cnt = 0;

        for(int i = 0 ; i < n;i++){
            if(a[i] % j){
                cnt++;
            }
            else{
                res += cnt;
                cnt = 0;
            }
        }
        ans = min(ans,res);

    }
    printf("%lld\n",ans);
    return 0;
}


#include <bits/stdc++.h>

#define ll long long
#define N ((int)1e6+10)
#define MOD ((int)1e9+7)

using namespace std;

int r, c, k, t, n;
ll a[N], b[N];
ll sum = 0;

ll calc(int l, int r, int x, ll sum) {
    ll res = 0;
    for (int i = l; i <= r; i++) {
        ll val = min(sum, b[i]);
        sum -= val;
        res += val * abs(i - x);
    }
    return res;
}

ll search(int l, int r, ll sum) {

    int s = l, e = r;
    while (r - l >= 3) {
        int m1 = l + (r - l) / 3;
        int m2 = r - (r - l) / 3;
        ll f1 = calc(s, e, m1, sum);      //evaluates the function at m1
        ll f2 = calc(s, e, m2, sum);      //evaluates the function at m2
        if (f1 > f2)
            r = m2;
        else
            l = m1;
    }
    ll ans = 1e18;
    for(int j = max(l,s) ; j <= min(e,r);j++){
        ans = min (ans,calc(s, e, j, sum));
    }
    return ans;
}

ll try_this(ll d) {
    ll res = 0;
    int l = 0, r = -1;
    ll s = 0;
    for(int i = 0 ; i < n;i++){
        b[i] = a[i];
    }
    for (int i = 0; i < n; i++) {
        if (a[i] == 0) {
            continue;
        }
        if (s == 0) {
            l = i;
        }
        s += a[i];
        r = i;

        if (s / d) {
            ll ds = s - (s % d);
            res += search(l, r, ds);
            s = s % d;
            b[i] = s;
            l = i;
        }
    }
    return res;
}

int main() {
    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &a[i]);
        sum += a[i];
    }
    if (sum == 1) {
        printf("%d\n", -1);
        return 0;
    }
    b[0] = a[0];
    for (int i = 1; i < n; i++) {
        b[i] += b[i - 1];
        b[i] += a[i];
    }
    ll ans = 1e18;
    for (ll j = 2; j * j <= sum; j++) {
        if (sum % j != 0)
            continue;
        ll g[2] = {j, sum / j};

        for (int e = 0; e < 2; e++) {

            ans = min(ans, try_this(g[e]));
        }
    }
    ans = min(ans,try_this(sum));
    printf("%lld\n", ans);
    return 0;
}


#include <bits/stdc++.h>

#define ll long long
#define N ((int)1e6+10)
#define MOD ((int)1e9+7)

using namespace std;

int r, c, k, t, n;
ll a[N], b[N];
ll sum = 0;

ll calc(int l, int r, int x, ll sum) {
    ll res = 0;
    for (int i = l; i <= r; i++) {
        ll val = min(sum, b[i]);
        sum -= val;
        res += val * abs(i - x);
    }
    return res;
}

ll search(int l, int r, ll sum) {

    int s = l, e = r;
    while (r - l >= 3) {
        int m1 = l + (r - l) / 3;
        int m2 = r - (r - l) / 3;
        ll f1 = calc(s, e, m1, sum);      //evaluates the function at m1
        ll f2 = calc(s, e, m2, sum);      //evaluates the function at m2
        if (f1 > f2)
            r = m2;
        else
            l = m1;
    }
    ll ans = 1e18;
    for (int j = max(l, s); j <= min(e, r); j++) {
        ans = min(ans, calc(s, e, j, sum));
    }
    return ans;
}

ll try_this(ll d) {
    ll res = 0;
    int l = 0, r = -1;
    ll s = 0;
    for (int i = 0; i < n; i++) {
        b[i] = a[i];
    }
    for (int i = 0; i < n; i++) {
        if (a[i] == 0) {
            continue;
        }
        if (s == 0) {
            l = i;
        }
        s += a[i];
        r = i;

        if (s / d) {
            ll ds = s - (s % d);
            res += search(l, r, ds);
            s = s % d;
            b[i] = s;
            l = i;
        }
    }
    return res;
}

int main() {

    scanf("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &a[i]);
        sum += a[i];
    }
    if (sum == 1) {
        printf("%d\n", -1);
        return 0;
    }

    vector<ll> f;
    ll s2 = sum;
    for (int i = 2; i * i <= sum; i++) {
        if (s2 % i == 0) {
            f.push_back(i);
        }
        while (s2 % i == 0) {
            s2 /= i;
        }
    }
    if (s2 > 1) {
        f.push_back(s2);
    }
    b[0] = a[0];
    for (int i = 1; i < n; i++) {
        b[i] += b[i - 1];
        b[i] += a[i];
    }
    ll ans = 1e18;
    for (ll j = 0; j < f.size(); j++) {
        ans = min(ans, try_this(f[j]));
    }
    ans = min(ans, try_this(sum));
    printf("%lld\n", ans);
    return 0;
}


#include <iostream>
#include <iosfwd>
#include <iomanip>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <cassert>
#include <cctype>
#include <climits>
#include <vector>
#include <bitset>
#include <set>
#include <queue>
#include <stack>
#include <map>
#include <deque>
#include <string>
#include <list>
#include <iterator>
#include <sstream>
#include <complex>
#include <fstream>
#include <functional>
#include <numeric>
#include <utility>
#include <algorithm>
#include <assert.h>
#include <unordered_map>

using namespace std;
const int N = 1e6 + 500;
const long long mod = 1e9 + 7;
const long long INF = 1LL << 57;
const int LN = 22;

long long n, m, u, v, k, t, q, x, d, p, a, b, c, s, e, g, r;

long long arr[N], brr[N];

long long solve(long long div) {
  for (int i = 1; i <= n; ++i) brr[i] = arr[i];

  long long extra = 0;
  long long medianLocation = -1;
  long long sol = 0;
  for (int i = 1; i <= n; ++i) {
    if (brr[i] % div == 0) continue;
    long long rem = brr[i] % div;
    if (medianLocation == -1) {
      sol += extra;
      long long temp = min(rem, div - extra);
      extra += temp;
      brr[i] -= temp;
      if (extra >= (div + 1) / 2) {
          medianLocation = i;
          extra = div - extra;
      }
    }

    if (medianLocation != -1) {
      long long rem = brr[i] % div;
      long long temp = min(rem, extra);
      extra -= temp;
      brr[i] -= temp;
      sol += (temp * (i - medianLocation));
    }

    if (medianLocation != -1 and extra == 0) {
      medianLocation = -1;
      if (brr[i] % div != 0) i--;
    }
  }

  return sol;
}
int main() {
  ios::sync_with_stdio(false);cin.tie(0);
  cin >> n;

  long long sum = 0;

  for (int i = 1; i <= n; ++i) {
    cin >> arr[i];
    sum += arr[i];
  }

  long long sol = sum * 1000000LL;
  bool valid = false;

  if (sum == 0) {
      cout << 0 << endl;
      return 0;
  }

  for (long long i = 2; i <= sum; ++i) {
    if (sum % i == 0) {
      sol = min(sol, solve(i));
      valid = true;
    }
    if (sum % i == 0 and sum / i != i and i != sum) {
      sol = min(sol, solve(sum / i));
      valid = true;
    }
  }

  if (valid) cout << sol << endl;
  else cout << -1 << endl;
}


#include <iostream>
#include <iosfwd>
#include <iomanip>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <cassert>
#include <cctype>
#include <climits>
#include <vector>
#include <bitset>
#include <set>
#include <queue>
#include <stack>
#include <map>
#include <deque>
#include <string>
#include <list>
#include <iterator>
#include <sstream>
#include <complex>
#include <fstream>
#include <functional>
#include <numeric>
#include <utility>
#include <algorithm>
#include <assert.h>
#include <unordered_map>

using namespace std;
const int N = 1e6 + 500;
const long long mod = 1e9 + 7;
const long long INF = 1LL << 57;
const int LN = 22;

long long n, m, u, v, k, t, q, x, d, p, a, b, c, s, e, g, r;

long long arr[N], brr[N];

long long solve(long long div) {
  for (int i = 1; i <= n; ++i) brr[i] = arr[i];

  long long sol = 0;

  for (int i = 1; i <= n; ++i) sol += min(brr[i] % div, div - (brr[i] % div));
  return sol;
}

vector <long long> prime;
int main() {
  ios::sync_with_stdio(false);cin.tie(0);
  cin >> n;

  long long sum = 0;

  for (int i = 1; i <= n; ++i) {
    cin >> arr[i];
    arr[i] += arr[i - 1];
  }

  if (arr[n] == 0) {
    cout << 0 << endl;
    return 0;
  }

  if (arr[n] == 1) {
    cout << -1 << endl;
    return 0;
  }

  long long temp = arr[n];

  for (long long i = 2; i * i <= arr[n]; ++i) {
    if (temp % i == 0) {
      prime.push_back(i);
      while (temp % i == 0) temp /= i;
    }
  }

  if (temp > 1) prime.push_back(temp);

  long long sol = solve(arr[n]);

  for (int i = 0; i < prime.size(); ++i) {
    sol = min(sol, solve(prime[i]));
  }

  cout << sol << endl;
}


#include <iostream>
#include <iosfwd>
#include <iomanip>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <cassert>
#include <cctype>
#include <climits>
#include <vector>
#include <bitset>
#include <set>
#include <queue>
#include <stack>
#include <map>
#include <deque>
#include <string>
#include <list>
#include <iterator>
#include <sstream>
#include <complex>
#include <fstream>
#include <functional>
#include <numeric>
#include <utility>
#include <algorithm>
#include <assert.h>
#include <unordered_map>

using namespace std;
const int N = 1e6 + 500;
const long long mod = 1e9 + 7;
const long long INF = 1LL << 57;
const int LN = 22;

long long n, m, u, v, k, t, q, x, d, p, a, b, c, s, e, g, r;

long long arr[N], brr[N];

long long solve(long long div) {
  for (int i = 1; i <= n; ++i) brr[i] = arr[i];

  long long extra = 0;
  long long medianLocation = -1;
  long long sol = 0;
  for (int i = 1; i <= n; ++i) {
    if (brr[i] % div == 0) continue;
    long long rem = brr[i] % div;
    if (medianLocation == -1) {
      sol += extra;
      long long temp = min(rem, div - extra);
      extra += temp;
      brr[i] -= temp;
      if (extra >= (div + 1) / 2) {
          medianLocation = i;
          extra = div - extra;
      }
    }

    if (medianLocation != -1) {
      long long rem = brr[i] % div;
      long long temp = min(rem, extra);
      extra -= temp;
      brr[i] -= temp;
      sol += (temp * (i - medianLocation));
    }

    if (medianLocation != -1 and extra == 0) {
      medianLocation = -1;
      if (brr[i] % div != 0) i--;
    }
  }

  return sol;
}
int main() {
  ios::sync_with_stdio(false);cin.tie(0);
  cin >> n;

  long long sum = 0;

  for (int i = 1; i <= n; ++i) {
    cin >> arr[i];
    sum += arr[i];
  }

  long long sol = sum * 1000000LL;
  bool valid = false;

  for (long long i = 2; i <= 1000000; ++i) {
    if (sum % i == 0) {
      sol = min(sol, solve(i));
      valid = true;
    }
    if (sum % i == 0 and sum / i != i) {
      sol = min(sol, solve(i));
      valid = true;
    }
  }

  if (valid) cout << sol << endl;
  else cout << -1 << endl;
}


#include<bits/stdc++.h>
#pragma warning(disable:4996)
using namespace std;
const int N = 1e5 + 10;
map<int, int> mp;
int prime[N];
int main() {
	int n, a[N] = { 0 }, cnt = 0, dis, ans = 0x3f3f3f3f;
	scanf("%d", &n);
	for (int i = 1; i <= n; i++) {
		scanf("%d", &a[i]);
		if (a[i]) cnt++;
	}
	//����ɸ��
	for (int i = 2; i <= cnt; i++) {
		if (!(prime[i])) {
			int x = i,l = 2;
			x *= l;
			while (x <= cnt) {
				prime[x] = 1;
				l++;
				x *= l;
			}
		}
	}

	if (cnt == 1) {
		printf("-1\n");
		return 0;
	}
	for (int k = 2; k <= cnt; k++) {
		if (!prime[k]) {
			int x = 0;
			dis = k;
			int j = 0;
			for (int i = 1; i <= n; i++) {
				if (a[i]) {
					j++;
					mp[j] = i;
					if (j == dis) {
						j = 0;
						for (int k = 1; k <= (dis / 2); k++) {
							x += (mp[dis - k + 1] - mp[k]);
						}
					}
				}
			}
			ans = min(ans, x);
		}
	}
	printf("%d\n", ans);
	return 0;
}


#include<bits/stdc++.h>
#pragma warning(disable:4996)
using namespace std;
const int N = 1e5 + 10;
map<int, int> mp;
int prime[N],a[N];
int main() {
	int n, cnt = 0, dis;
	long long ans = 0x3f3f3f3f3f3f3f3f;
	scanf("%d", &n);
	for (int i = 1; i <= n; i++) {
		scanf("%d", &a[i]);
		if (a[i]) cnt++;
	}
	//����ɸ��
	for (int i = 2; i <= cnt; i++) {
		if (!(prime[i])) {
			int x = i,l = 2;
			x *= l;
			while (x <= cnt) {
				prime[x] = 1;
				l++;
				x *= l;
			}
		}
	}

	if (cnt == 1) {
		printf("-1\n");
		return 0;
	}
	for (int k = 2; k <= cnt; k++) {
		if ((!prime[k]) && (cnt % k == 0)) {
			long long x = 0;
			dis = k;
			int j = 0;
			for (int i = 1; i <= n; i++) {
				if (a[i]) {
					j++;
					mp[j] = i;
					if (j == dis) {
						j = 0;
						for (int k = 1; k <= (dis / 2); k++) {
							x += (mp[dis - k + 1] - mp[k]);
						}
					}
				}
			}
			ans = min(ans, x);
		}
	}
	printf("%lld\n", ans);
	return 0;
}


#include<bits/stdc++.h>
#pragma warning(disable:4996)
using namespace std;
const int N = 1e5 + 10;
map<int, int> mp;
int prime[N];
int main() {
	int n, a[N] = { 0 }, cnt = 0, dis, ans = 0x3f3f3f3f;
	scanf("%d", &n);
	for (int i = 1; i <= n; i++) {
		scanf("%d", &a[i]);
		if (a[i]) cnt++;
	}
	//����ɸ��
	for (int i = 2; i <= cnt; i++) {
		if (!(prime[i])) {
			int x = i,l = 2;
			while (x <= cnt) {
				x *= l;
				prime[x] = 1;
				l++;
			}
		}
	}

	if (cnt == 1) {
		printf("-1\n");
		return 0;
	}
	for (int k = 2; k <= cnt; k++) {
		if (!prime[k]) {
			int x = 0;
			dis = k;
			int j = 0;
			for (int i = 1; i <= n; i++) {
				if (a[i]) {
					j++;
					mp[j] = i;
					if (j == dis) {
						j = 0;
						for (int k = 1; k <= (dis / 2); k++) {
							x += (mp[dis - k + 1] - mp[k]);
						}
					}
				}
			}
			ans = min(ans, x);
		}
	}
	printf("%d\n", ans);
	return 0;
}


#include<bits/stdc++.h>
#pragma warning(disable:4996)
using namespace std;
const int N = 1e5 + 10;
map<int, int> mp;
int prime[N],a[N];
int main() {
	int n, cnt = 0, dis, ans = 0x3f3f3f3f;
	scanf("%d", &n);
	for (int i = 1; i <= n; i++) {
		scanf("%d", &a[i]);
		if (a[i]) cnt++;
	}
	//����ɸ��
	for (int i = 2; i <= cnt; i++) {
		if (!(prime[i])) {
			int x = i,l = 2;
			x *= l;
			while (x <= cnt) {
				prime[x] = 1;
				l++;
				x *= l;
			}
		}
	}

	if (cnt == 1) {
		printf("-1\n");
		return 0;
	}
	for (int k = 2; k <= cnt; k++) {
		if ((!prime[k]) && (cnt % k == 0)) {
			int x = 0;
			dis = k;
			int j = 0;
			for (int i = 1; i <= n; i++) {
				if (a[i]) {
					j++;
					mp[j] = i;
					if (j == dis) {
						j = 0;
						for (int k = 1; k <= (dis / 2); k++) {
							x += (mp[dis - k + 1] - mp[k]);
						}
					}
				}
			}
			ans = min(ans, x);
		}
	}
	printf("%d\n", ans);
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1000005;
int n,a[N],ans;
bool check(int x)
{
	if(x==3)
	{
		for(int i=1,j=1;i<=n;i=j)if(a[i])
		{
			for(;a[j]==a[i];j++);
			if((j-i)%x)return 0;
		}return 1;
	}else
	{
		int lst=0;
		for(int i=1;i<=n;i++)
		{
			if(lst&&(a[i]+a[i+1]==0))return 0;
			if(lst&&a[i])lst=0,a[i]=0;
			else if(lst&&a[i+1])a[i+1]=lst=0;
			if(a[i])lst=1;
		}
		if(lst)return 0;return 1;
	}
}
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++)scanf("%d",&a[i]);
	if(check(3))return puts("3"),0;if(check(2))return puts("2"),0;puts("-1");
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1000005;
int n,a[N];ll sum,ans;
ll check(ll x)
{
	ll now = 0 , pos = 0 , ret = 0;
	for(int i=1;i<=n;i++)
	{
		if(pos)ret+=min(a[i]%x,x-now)*(i-pos);
		now+=a[i]%x;
		// printf("%d %lld %lld %lld\n",i,now,x,pos);
		if(now>=x)now%=x,pos=0;
		if(!pos&&now>=(x+1)/2)pos = i;
		if(!pos)ret+=now;
	}
	return ret;
}
int main()
{
	scanf("%d",&n);ans = 1ll<<60;
	for(int i=1;i<=n;i++)scanf("%d",&a[i]),sum+=a[i];
	for(int i=2;i<=sum/i;i++)
		if(sum%i==0)
		{
			ans = min(ans,check(i));
			while(sum%i==0)sum/=i;
		}
	if(sum!=1)ans = min(ans,check(sum));
	if(ans == (1ll<<60))return puts("-1"),0;
	printf("%lld\n",ans);
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1000005;
int n,a[N],ans;
bool check(int x)
{
	if(x==3)
	{
		for(int i=1,j=1;i<=n;i=j)
			if(a[i])
			{
				for(;j<=n&&a[j]==a[i];j++);
				if((j-i)%x)return 0;
			}else j=i+1;
		return 1;
	}else
	{
		int lst=0;
		for(int i=1;i<=n;i++)
		{
			if(lst&&(a[i]+a[i+1]==0))return 0;
			if(lst&&a[i])lst=0,a[i]=0;
			else if(lst&&a[i+1])a[i+1]=lst=0;
			if(a[i])lst=1;
		}
		if(lst)return 0;return 1;
	}
}
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++)scanf("%d",&a[i]);
	if(check(3))return puts("3"),0;if(check(2))return puts("2"),0;puts("-1");
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1000005;
int n,a[N],ans;
bool check(int x)
{
	int ret=0;
	if(x==3)
	{
		for(int i=1,j=1;i<=n;i=j)
			if(a[i])
			{
				for(;j<=n&&a[j]==a[i];j++);
					ret+=((j-i)/3)*2;
				if((j-i)%x)return 0;
			}else j=i+1;
		ans=min(ans,ret);return 1;
	}else
	{
		int lst=0;
		for(int i=1;i<=n;i++)
		{
			if(lst&&(a[i]+a[i+1]==0))return 0;
			if(lst&&a[i])lst=0,a[i]=0,ret++;
			else if(lst&&a[i+1])a[i+1]=lst=0,ret+=2;
			if(a[i])lst=1;
		}
		if(lst)return 0;ans=min(ans,ret);return 1;
	}
}
int main()
{
	scanf("%d",&n);ans = 1<<30;
	for(int i=1;i<=n;i++)scanf("%d",&a[i]);
	check(3),check(2);
	if(ans == (1<<30))puts("-1");else printf("%d\n",ans);
}


#include<bits/stdc++.h>
using namespace std;
#define pii pair<int,int>
#define ll long long
#define pb push_back
#define fi first
#define se second
#define mp make_pair
#define abs(x) ((x)>0?(x):-(x))
#define INF 1e18
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
   int n;
   cin>>n;
   int ara[n];
   vector<int> v,div;
   for(int i=0;i<n;i++)
    cin>>ara[i];
   for(int i=0;i<n;i++)
    if(ara[i]) v.pb(i);
    int sum=v.size();
    int k=sum;
   for(int i=2;i*i<=sum;i++)
    if(sum%i==0)
   {
       div.pb(i);
       div.pb(sum/i);
   }
   div.pb(sum);
   if(sum==1)
   {
       cout<<-1<<endl;
       return 0;
   }
ll cnt=0;
ll mn=INF;
for(int j=0;j<div.size();j++)
{
    int k=div[j];
    int mid=k/2;
    int la=0;
     cnt=0;
       while(la+1<sum)
       {
           for(int i=la;i<la+mid;i++)
            {cnt+=(v[la+mid]-v[i]);
            //cout<<cnt<<endl;
            }
           for(int i=la+mid+1;i<la+k;i++)
            {
                cnt+=(v[i]-v[la+mid]);
                //cout<<cnt<<endl;
            }
           la+=k;
       }
       //cout<<k<<' '<<cnt<<endl;
       mn=min(cnt,mn);
}
   cout<<mn<<endl;
}


#include<bits/stdc++.h>
using namespace std;
#define pii pair<int,int>
#define ll long long
#define pb push_back
#define fi first
#define se second
#define mp make_pair
#define abs(x) ((x)>0?(x):-(x))
#define INF 1e18
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
   int n;
   cin>>n;
   int ara[n];
   vector<int> v,div;
   for(int i=0;i<n;i++)
    cin>>ara[i];
   for(int i=0;i<n;i++)
    if(ara[i]) v.pb(i);
    int sum=v.size();
    int k=sum;
   for(int i=2;i*i<=sum;i++)
    if(sum%i==0)
   {
       div.pb(i);
       div.pb(sum/i);
   }
   div.pb(sum);
   if(sum==1)
   {
       cout<<-1<<endl;
       return 0;
   }
   int la=0;
int mid=k/2;
ll cnt=0;
ll mn=INF;
for(int i=0;i<div.size();i++)
{
    int k=div[i];
    int mid=k/2;
    int la=0;
    ll cnt=0;
       while(la+1<sum)
       {
           for(int i=la;i<la+mid;i++)
            {cnt+=(v[la+mid]-v[i]);
            //cout<<cnt<<endl;
            }
           for(int i=la+mid+1;i<la+k;i++)
            {
                cnt+=(v[i]-v[la+mid]);
                //cout<<cnt<<endl;
            }
           la+=k;
       }
       mn=min(cnt,mn);
}
   cout<<cnt<<endl;
}


#include<bits/stdc++.h>
using namespace std;
#define pii pair<int,int>
#define ll long long
#define pb push_back
#define fi first
#define se second
#define mp make_pair
#define abs(x) ((x)>0?(x):-(x))
#define INF 1e18
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
   int n;
   cin>>n;
   int ara[n];
   vector<int> v,div;
   for(int i=0;i<n;i++)
    cin>>ara[i];
   for(int i=0;i<n;i++)
    if(ara[i]) v.pb(i);
    int sum=v.size();
    int k=sum;
   for(int i=2;i*i<=sum;i++)
    if(sum%i==0)
   {
       div.pb(i);
       div.pb(sum/i);
   }
   div.pb(sum);
   if(sum==1)
   {
       cout<<-1<<endl;
       return 0;
   }
ll cnt=0;
ll mn=INF;
for(int j=0;j<div.size();j++)
{
    int k=div[j];
    int mid=k/2;
    int la=0;
     cnt=0;
       while(la+1<sum)
       {
           for(int i=la;i<la+mid;i++)
            {cnt+=(v[la+mid]-v[i]);
            //cout<<cnt<<endl;
            }
           for(int i=la+mid+1;i<la+k;i++)
            {
                cnt+=(v[i]-v[la+mid]);
                //cout<<cnt<<endl;
            }
           la+=k;
       }
       //cout<<cnt<<endl;
       mn=min(cnt,mn);
}
   cout<<cnt<<endl;
}


#include <bits/stdc++.h>
using namespace std;

#define fi first
#define se second
#define all(x) (x).begin(), (x).end()
#define pb push_back
#define endl '\n'

typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;

const int INF = 1e9;
const ll MOD = 1e9 + 7;
const int MAXN = 1e5 + 5;

int N, A[MAXN];

int main() {
	ios::sync_with_stdio(0); cin.tie(0);

	cin >> N;
	int cnt = 0;
	for(int i=1; i<=N; i++) cin >> A[i], cnt += A[i];

	if(cnt % 2) {
		cout << -1;
		return 0;
	}

	int has = -1, ans = 0;
	for(int i=1; i<=N; i++) {
		if(A[i]) {
			if(has == -1) has = i;
			else {
				ans += i - has;
				has = -1;
			}
		}
	}
	cout << ans;
}


#include <bits/stdc++.h>
using namespace std;

#define fi first
#define se second
#define all(x) (x).begin(), (x).end()
#define pb push_back
#define endl '\n'

typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;

const int INF = 1e9;
const ll MOD = 1e9 + 7;
const int MAXN = 1e5 + 5;

ll N, A[MAXN], B[MAXN];
vector<int> V;

int main() {
	ios::sync_with_stdio(0); cin.tie(0);

	cin >> N;
	for(int i=1; i<=N; i++) {
		int x; cin >> x;
		if(x) V.pb(i);
	}

	if(V.size() == 1) {
		cout << -1;
		return 0;
	}

	for(int i=1; i<V.size(); i++) {
		A[i] = A[i-1] + V[i]-V[i-1];
		B[i] = B[i-1] + A[i];
	}

	ll ans = 1e18;
	for(int i=2; i<=V.size(); i++) if(V.size() % i == 0) {
		ll sum = 0;
		for(int j=0; j<V.size(); j+=i) {
			int mid = j + (i/2);
			int l = j, r;
			if(i % 2 == 0) r = mid + (i/2) - 1;
			else r = mid + (i/2);

			sum += (B[r]-B[mid]) - (r-mid) * A[mid];
			sum += (mid-l+1) * A[mid] - (B[mid]-B[max(0,l-1)]);
		}
		ans = min(ans, sum);
	}

	cout << ans;
}


#include <bits/stdc++.h>
using namespace std;

#define fi first
#define se second
#define all(x) (x).begin(), (x).end()
#define pb push_back
#define endl '\n'

typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;

const int INF = 1e9;
const ll MOD = 1e9 + 7;
const int MAXN = 1e5 + 5;

ll N, A[MAXN], B[MAXN];
vector<int> V;

int main() {
	ios::sync_with_stdio(0); cin.tie(0);

	cin >> N;
	for(int i=1; i<=N; i++) {
		int x; cin >> x;
		if(x) V.pb(i);
	}

	if(V.size() == 1) {
		cout << -1;
		return 0;
	}

	for(int i=1; i<V.size(); i++) {
		A[i] = A[i-1] + V[i]-V[i-1];
		B[i] = B[i-1] + A[i];
	}

	ll ans = 1e18;
	for(int i=2; i<=V.size(); i++) if(V.size() % i == 0) {
		ll sum = 0;
		for(int j=0; j<V.size(); j+=i) {
			int mid = i + (i/2);
			int l = i, r;
			if(i % 2) r = mid + (i/2) - 1;
			else r = mid + (i/2);

			sum += (B[r]-B[mid]) - (r-mid) * A[mid];
			sum += (mid-l) * A[mid] - (B[mid-1]-B[max(0,l-1)]);
		}
		ans = min(ans, sum);
	}

	cout << ans;
}


#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/hash_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
using namespace __gnu_cxx;
#ifdef local
  #define readfromfile(file) freopen(file, "r", stdin)
  #define debug(...) { cerr << __LINE__ << " : \
     [" << #__VA_ARGS__ << "] = ["; err(__VA_ARGS__); cerr << "]\n";}
  template<class T>
  void err(T x) { cerr << x;}
  template<class T, class...Args>
  void err(T x, Args... args){ cerr << x << ", ";err(args...);}
#else
  #define debug(...)
  #define readfromfile(...)
  #define endl '\n'
  #define cerr if(0)cout
  #define err(...)
#endif
#define fi first
#define se second
#define empb emplace_back
#define bk back
#define ppb pop_back
#define ins insert
#define clr(a, b) memset(a, b, sizeof a)
#define rep(i, n) for(int i = 0; i < n; i++)
#define ls rt << 1
#define rs rt<<1|1
#define inf 0x3f3f3f3f
#define all(x) (x).begin(),(x).end()
typedef long long ll;
typedef vector<int> VI;
typedef pair<int, int> pii;
typedef long double ldb;
typedef complex<double> cpd;
const int N = 3e5 + 7, M = 1 << 10;
const double pi = acos(-1.0);
const int P = 7 * 17 << 23 | 1, G = 3;
const int mod = 1e9 + 7;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(0), cout.tie(0);
  readfromfile("in.txt");
  int n; cin >> n;
  vector<int> a(n);
  int cnt = 0;
  for(int i = 0; i < n; i++) {
    cin >> a[i];
    cnt += a[i] == 1;
  }
  if(cnt == 1) return cout << -1 << endl, 0;
  int res = cnt;
  for(int i = 2; i * i <= cnt; i++) {
    if(cnt % i == 0) {
      res = i; break;
    }
  }
  int ans = 0;
  for(int i = 0; i < n; i++) {
    if(a[i] == 1) {
      int j = i;
      int c = 0;
      while(j < n && c < res) {
        c += a[j] == 1;
        j++;
      }
      ans += j - i - 1;
      i = j - 1;
    }
  }
  cout << ans << endl;
  cerr << clock() << " ms\n";
  return 0;
}