CodeEff/ECCO huggingface dataset:
# Original solution
W,H=list(map(int,input().split()))
P=[int(eval(input())) for i in range(W)]
Q=[int(eval(input())) for j in range(H)]
P.append(float('inf'))
Q.append(float('inf'))
P.sort(reverse=True)
Q.sort(reverse=True)
now_W=W+1
now_H=H+1
cost=0
while now_W>1 or now_H>1:
    if P[-1]<Q[-1]:
        cost+=P.pop()*now_H
        now_W-=1
    elif Q[-1]<P[-1]:
        cost+=Q.pop()*now_W
        now_H-=1
    elif P[-1]==Q[-1]:
        if now_W<=now_H:
            cost+=Q.pop()*now_W
            now_H-=1
        elif now_W>now_H:
            cost+=P.pop()*now_H
            now_W-=1
print(cost)

# Optimized solution
import sys
input=sys.stdin.readline
W,H=list(map(int,input().split()))
P=[int(eval(input())) for _ in range(W)]+[float('inf')]
Q=[int(eval(input())) for _ in range(H)]+[float('inf')]
P.sort(reverse=True)
Q.sort(reverse=True)
ans=0
W+=1
H+=1
while True:
    if W==H==1:
        break
    elif Q[-1]<P[-1] or (Q[-1]==P[-1] and W<=H):
        ans+=W*Q[-1]
        H-=1
        Q.pop()
    elif Q[-1]>P[-1] or (Q[-1]==P[-1] and W>H):
        ans+=H*P[-1]
        W-=1
        P.pop()
print(ans)
# Original solution
W,H = list(map(int,input().split()))

side = []
for i in range(W):
    side.append({"cost":int(eval(input())),"num":i,"dir":0})
for i in range(H):
    side.append({"cost":int(eval(input())),"num":i,"dir":1})
side = sorted(side,key = lambda x:x["cost"])

node =[[{"v":j,"men":[j]} for j in range(i*(W+1),(i+1)*(W+1))]for i in range(H+1)]
ans = 0
for s in side:
    cost,num,di = s["cost"],s["num"],s["dir"]
    if di == 0 :
        for i in range(H+1):
            if node[i][num]["v"] != node[i][num+1]["v"]: # 親が違ったら
                # print(i,num,0)
                ans += cost
                v1 = node[i][num]["v"]
                v2 = node[i][num+1]["v"]
                
                for j in node[v2//(W+1)][v2%(W+1)]["men"]: # v2とつながった要素の親を書き換え
                    node[j//(W+1)][j%(W+1)]["v"] = v1
                node[v1//(W+1)][v1%(W+1)]["men"] += node[v2//(W+1)][v2%(W+1)]["men"]
    else:
        for i in range(W+1):
            if node[num][i]["v"] != node[num+1][i]["v"]: # 親が違ったら
                # print(num,i,1)
                ans += cost
                v1 = node[num][i]["v"]
                v2 = node[num+1][i]["v"]
                
                for j in node[v2//(W+1)][v2%(W+1)]["men"]: # v2とつながった要素の親を書き換え
                    node[j//(W+1)][j%(W+1)]["v"] = v1
                node[v1//(W+1)][v1%(W+1)]["men"] += node[v2//(W+1)][v2%(W+1)]["men"]
print(ans)



# Optimized solution
W, H = list(map(int, input().split()))

side = [{"cost":int(eval(input())), "di":0}for i in range(W)] + [{"cost":int(eval(input())), "di":1}for i in range(H)]
side = sorted(side, key=lambda x:x["cost"])
ans = 0
ty = [H+1,W+1]
for s in side:
    cost, di = s["cost"], s["di"]
    ans += ty[di] * cost
    ty[(di+1)%2] -= 1
print(ans)
# Original solution
def main():
    import sys
    input = sys.stdin.readline
    from bisect import bisect_left, bisect_right


    W, H = list(map(int, input().split()))
    P = [int(eval(input())) for _ in range(W)]
    P.sort()
    P_count = [0] * (W + 2)

    Q = [int(eval(input())) for _ in range(H)]
    Q.sort()

    ans = 0
    for q in Q:
        tmp = bisect_right(P, q)
        P_count[tmp] += 1
        ans += q * (1 + W - tmp)

    for i in range(W, - 1, -1):
        P_count[i] += P_count[i + 1]
    # print ('途中', ans)
    # for p in P:
    #     tmp = bisect_left(Q, p)
    #     ans += p * (1 + H - tmp)
    for index, p in enumerate(P):
        ans += p * (P_count[index + 1] + 1)
    print (ans)
    # print ('P:', P)
    # print ('Q:', Q)

if __name__ == '__main__':
    main()

# Optimized solution
def main():
    import sys
    input = sys.stdin.readline
    from bisect import bisect_right

    W, H = list(map(int, input().split()))
    P = [int(eval(input())) for _ in range(W)]
    P.sort()
    P_count = [0] * (W + 2)

    Q = [int(eval(input())) for _ in range(H)]
    Q.sort()

    ans = 0
    for q in Q:
        tmp = bisect_right(P, q)
        P_count[tmp] += 1
        ans += q * (1 + W - tmp)

    for i in range(W, - 1, -1):
        P_count[i] += P_count[i + 1]

    for index, p in enumerate(P):
        ans += p * (P_count[index + 1] + 1)

    print (ans)

if __name__ == '__main__':
    main()
# Original solution
ss=input().split()
w=int(ss[0])
h=int(ss[1])
a=[]
b=[]
for i in range( w):
    p=eval(input())
    a.append( p)
for i in range( h):
    p=eval(input())
    b.append( p)
a.sort()
b.sort()
h1=0
h2=0
ans=0
while ((h1<w) and (h2<h)):
    if a[h1]<b[h2]:
        ans+=a[h1]*(h - h2+1)
        h1+=1
    else :
        ans += b[h2] * (w-h1+1)
        h2 += 1
while (h1<w):
    ans+=a[h1]
    h1+=1
while (h2<h):
    ans+=b[h2]
    h2+=1
print(ans)

# Optimized solution
ss=input().split()
w=int(ss[0])
h=int(ss[1])

a=[]
b=[]

for i in range(w):
    p=eval(input())
    a.append(p)
for i in range(h):
    p=eval(input())
    b.append(p)

a.sort()
b.sort()

h1=0
h2=0
res=0

while h1 < w and h2 < h:
    if a[h1]<b[h2]:
        res += a[h1] * (h - h2 + 1)
        h1 += 1
    else:
        res += b[h2] * (w - h1 + 1)
        h2 += 1
while (h1<w):
    res += a[h1]
    h1 += 1
while (h2<h):
    res += b[h2]
    h2 += 1
print(res)
# Original solution
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(W, H, P, Q):
    W += 1
    H += 1
    ans = 0
    for i, p in enumerate(P):
        ans += p

    for i, q in enumerate(Q):
        ans += q


    for i in range(1, H):
        for j in range(1, W):
            if P[j-1] < Q[i-1]:
                ans += P[j-1]
            else:
                ans += Q[i-1]

    return ans


def main():
    W, H = read_int_n()
    P = [read_int() for _ in range(W)]
    Q = [read_int() for _ in range(H)]
    print(slv(W, H, P, Q))


if __name__ == '__main__':
    main()


# Optimized solution
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(W, H, P, Q):
    W += 1
    H += 1
    ans = sum(P) + sum(Q)

    P.sort()
    Q.sort()
    # print(P)
    for q in Q:
        i = bisect.bisect_left(P, q)
        # print(i, q)
        ans += q * (len(P)-i)
    for p in P:
        i = bisect.bisect_right(Q, p)
        # print(i, p)
        ans += p * (len(Q)-i)

    return ans


def main():
    W, H = read_int_n()
    P = [read_int() for _ in range(W)]
    Q = [read_int() for _ in range(H)]
    print(slv(W, H, P, Q))


if __name__ == '__main__':
    main()
# Original solution
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(W, H, P, Q):
    W += 1
    H += 1
    ans = sum(P) + sum(Q)

    P.sort()
    Q.sort()
    # print(P)
    for q in Q:
        i = bisect.bisect_left(P, q)
        # print(i, q)
        ans += q * (len(P)-i)
    for p in P:
        i = bisect.bisect_right(Q, p)
        # print(i, p)
        ans += p * (len(Q)-i)

    return ans


def main():
    W, H = read_int_n()
    P = [read_int() for _ in range(W)]
    Q = [read_int() for _ in range(H)]
    print(slv(W, H, P, Q))


if __name__ == '__main__':
    main()


# Optimized solution
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
from operator import add, mul, sub

sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input().strip()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(W, H, P, Q):
    ans = sum(P) + sum(Q)

    P.sort()
    Q.sort()
    for q in Q:
        i = bisect.bisect_left(P, q)
        ans += q * (len(P)-i)
    for p in P:
        i = bisect.bisect_right(Q, p)
        ans += p * (len(Q)-i)

    return ans


def main():
    W, H = read_int_n()
    P = [read_int() for _ in range(W)]
    Q = [read_int() for _ in range(H)]
    print(slv(W, H, P, Q))


if __name__ == '__main__':
    main()
# Original solution
W,H = list(map(int,input().split()))
PQ = [(int(eval(input())),0,i) for i in range(W)] + [(int(eval(input())),1,i) for i in range(H)]
PQ.sort()

import sys
sys.setrecursionlimit(10**7)

class UnionFind:
    def __init__(self):
        self.Parent = {}
    def add(self,k):
        self.Parent[k] = k
    def get_Parent(self,n):
        if self.Parent[n] == n:return n
        p = self.get_Parent(self.Parent[n])
        self.Parent[n] = p
        return p
    def merge(self,x,y):
        x = self.get_Parent(x)
        y = self.get_Parent(y)
        if x!=y: self.Parent[y] = x
        return
    def is_united(self,x,y):
        return self.get_Parent(x)==self.get_Parent(y)

ans = 0
T = UnionFind()
for i in range(W+1):
    for j in range(H+1):
        T.add((i,j))
for c,pq,ij in PQ:
    if pq==0:
        i = ij
        for j in range(H+1):
            if not T.is_united((i,j),(i+1,j)):
                T.merge((i,j),(i+1,j))
                ans += c
    else:
        j = ij
        for i in range(W+1):
            if not T.is_united((i,j),(i,j+1)):
                T.merge((i,j),(i,j+1))
                ans += c
print(ans)

# Optimized solution
W,H = list(map(int,input().split()))
PQ = [(int(eval(input())),0) for _ in [0]*W] + [(int(eval(input())),1) for _ in [0]*H]
PQ.sort()
r = H+1
c = W+1
ans = 0
for d,pq in PQ:
    if pq==0:
        ans += d*r
        c -=1
    else:
        ans += d*c
        r -=1
print(ans)
# Original solution
t = input()
W, H = list(map(int, t.split(' ')))
p, q = [], []
for i in range(W):
    p.append(int(input()))
for j in range(H):
    q.append(int(input()))

node = [
    (i, j, min(p[i-1] if i > 0 else 100000005, q[j-1] if j > 0 else 100000005)) for i in range(W+1) for j in range(H+1)
]
cost = 0
for i in range(W*H+W+H):
    cost += node[i+1][2]
print(cost)

# Optimized solution
t = input()
W, H = list(map(int, t.split(' ')))
p, q = [], []
for i in range(W):
    p.append(int(input()))
for j in range(H):
    q.append(int(input()))

cost = 0
for i in range(W+1):
    for j in range(H+1):
        if i == 0 and j == 0: continue
        cost += min(p[i-1] if i > 0 else 100000005, q[j-1] if j > 0 else 100000005)
print(cost)
# Original solution
t,*p=open(0)
w,h=list(map(int,t.split())) 
c=0
for v,f in sorted((t,i<w)for i,t in enumerate(map(int,p))):
  c-=~h*v*f or~w*v
  w-=f
  h-=1^f
print(c)

# Optimized solution
t,*p=open(0)
w,h=list(map(int,t.split())) 
c=0
for v,f in sorted((int(t),i<w)for i,t in enumerate(p)):
  c-=~h*v*f or~w*v
  w-=f
  h-=1^f
print(c)
# Original solution
W, H = list(map(int, input().split()))
p = sorted([(i, int(input())) for i in range(W)], key=lambda x:-x[1])
q = sorted([(i, int(input())) for i in range(H)], key=lambda x:-x[1])

class UnionFind(object):
    def __init__(self, n):
        self.uf = [-1 for _ in range(n)]

    def union(self, x, y):
        x = self.find(x[0] + x[1]*(W+1))
        y = self.find(y[0] + y[1]*(W+1))
        if x == y:
            return False
        if self.uf[x] >= self.uf[y]:
            self.uf[y] += self.uf[x]
            self.uf[x] = y
        else:
            self.uf[x] += self.uf[y]
            self.uf[y] = x
        return True

    def find(self, x):
        leaves = []
        while self.uf[x] >= 0:
            leaves.append(x)
            x = self.uf[x]
        for lf in leaves:
            self.uf[lf] = x
        return x

uf = UnionFind((W+1)*(H+1))
ans = 0
while len(p) > 0 or len(q) > 0:
    if len(q) == 0 or (len(p) > 0 and p[-1][1] <= q[-1][1]):
        i, cost = p.pop()
        for j in range(H+1):
            if uf.union((i, j), (i+1, j)):
                ans += cost
    else:
        j, cost = q.pop()
        for i in range(W+1):
            if uf.union((i, j), (i, j+1)):
                ans += cost
print(ans)


# Optimized solution
W, H = list(map(int, input().split()))
p = sorted([(i, int(input())) for i in range(W)], key=lambda x:-x[1])
q = sorted([(i, int(input())) for i in range(H)], key=lambda x:-x[1])
ans = 0
pe, qe, ae = 0, 0, (W+1)*(H+1)-1
while len(p)> 0 or len(q) > 0:
    if len(q) == 0 or (len(p) > 0 and p[-1][1] <= q[-1][1]):
        i, cost = p.pop()
        pe += 1
        ans += cost*(H+1-qe)
    else:
        j, cost = q.pop()
        qe += 1
        ans += cost*(W+1-pe)

print(ans)
# Original solution
n,q=list(map(int,input().split()))
exist=set([1])
cup=list(range(n+2))
now=1
exist.add(cup[now-1])
exist.add(cup[now+1])
for i in range(q):
    a,b=list(map(int,input().split()))
    if now==a:now=b
    elif now==b:now=a
    tmp=cup[a]
    cup[a]=cup[b]
    cup[b]=tmp
    exist.add(cup[now-1])
    exist.add(cup[now+1])
exist=list(exist)
ans=0
for i in range(len(exist)):
    if exist[i]!=0 and exist[i]!=n+1:ans+=1
print(ans)

# Optimized solution
n,q=list(map(int,input().split()))
exist=[False]*(n+2)
exist[1]=True
cup=list(range(n+2))
now=1
exist[cup[now-1]]=True
exist[cup[now+1]]=True
for i in range(q):
    a,b=list(map(int,input().split()))
    if now==a:now=b
    elif now==b:now=a
    tmp=cup[a]
    cup[a]=cup[b]
    cup[b]=tmp
    exist[cup[now-1]]=True
    exist[cup[now+1]]=True
ans=0
for i in range(1,n+1):
    if exist[i]:ans+=1
print(ans)
# Original solution
j=lambda:list(map(int,input().split()))
n,q=j()
c=[1,-1,1]+[0]*(n-2)+[1]
for p in[-1]*q:a,b=j();c[a],c[b]=c[b],c[a];i=c.index(p);c[i-1]=c[i+1]=1
print(sum(c))

# Optimized solution
j=lambda:list(map(int,input().split()))
n,q=j()
u=1
c=[1]*3+[0]*(n-2)+[1]
for p in[-1]*q:a,b=d=j();u+=u in d and a+b-2*u;c[a],c[b]=c[b],c[a];c[u-1]=c[u+1]=1
print(sum(c)-2)
# Original solution
#!/usr/bin/env python

from collections import deque
import itertools as it
import sys

sys.setrecursionlimit(1000000)

while True:
    S_ = input()
    if S_ == '.':
        break

    ans = 0
    for p, q, r in it.product([0, 1, 2], repeat = 3):
        S = S_
        S = S.replace("P", str(p)).replace("Q", str(q)).replace("R", str(r))

        for loop in range(100):
            S = S.replace("-0", "2")
            S = S.replace("-1", "1")
            S = S.replace("-2", "0")
            for a, b in it.product([0, 1, 2], repeat = 2):
                S = S.replace("(%d*%d)" % (a, b), str(min(a, b)))
                S = S.replace("(%d+%d)" % (a, b), str(max(a, b)))
            
        if S == "2":
            ans += 1
    print(ans)


# Optimized solution
#!/usr/bin/env python

from collections import deque
import itertools as it
import sys

sys.setrecursionlimit(1000000)

while True:
    S_ = input()
    if S_ == '.':
        break

    ans = 0
    for p, q, r in it.product([0, 1, 2], repeat = 3):
        S = S_
        S = S.replace("P", str(p)).replace("Q", str(q)).replace("R", str(r))

        while len(S) != 1:
            S = S.replace("-0", "2")
            S = S.replace("-1", "1")
            S = S.replace("-2", "0")
            for a, b in it.product([0, 1, 2], repeat = 2):
                S = S.replace("(%d*%d)" % (a, b), str(min(a, b)))
                S = S.replace("(%d+%d)" % (a, b), str(max(a, b)))
            
        if S == "2":
            ans += 1
    print(ans)
# Original solution
import sys
import itertools
input = sys.stdin.readline
sys.setrecursionlimit(100000)
mod = 10 ** 9 + 7

def read_values(): return list(map(int, input().split()))
def read_index(): return [int(x) - 1 for x in input().split()]
def read_list(): return list(read_values())
def read_lists(N): return [read_list() for n in range(N)]


class V:
    def __init__(self, f, v=None):
        self.f = f
        self.v = v
 
    def __str__(self):
        return str(self.v)
 
    def ud(self, n):
        if self.v is None:
            self.v = n
        else:
            self.v = self.f(self.v, n) 


def main():
    N = int(eval(input()))
    S = read_list()

    res = V(max, 0)
    for c in range(1, N):
        r = 0
        t1 = 0
        t2 = N - 1
        a = t2 - c
        while True:
            if a < c:
                break
            
            if (N - 1) % c == 0 and 2 * a <= N - 1:
                break

            t1 += c
            t2 -= c
            a -= c
            r += S[t1] + S[t2]
            res.ud(r)

    print(res)


if __name__ == "__main__":
    main()


# Optimized solution
import sys
import itertools
input = sys.stdin.readline
sys.setrecursionlimit(100000)
mod = 10 ** 9 + 7

def read_values(): return list(map(int, input().split()))
def read_index(): return [int(x) - 1 for x in input().split()]
def read_list(): return list(read_values())
def read_lists(N): return [read_list() for n in range(N)]


class V:
    def __init__(self, f, v=None):
        self.f = f
        self.v = v
 
    def __str__(self):
        return str(self.v)
 
    def ud(self, n):
        if self.v is None:
            self.v = n
        else:
            self.v = self.f(self.v, n) 


def main():
    N = int(eval(input()))
    S = read_list()

    res = V(max, 0)
    for c in range(1, N):
        r = 0
        t1 = 0
        t2 = N - 1
        while True:
            t1 += c
            t2 -= c
            if t2 < c:
                break
            
            if (N - 1) % c == 0 and 2 * t2 <= N - 1:
                break

            r += S[t1] + S[t2]
            res.ud(r)

    print(res)


if __name__ == "__main__":
    main()
# Original solution
N = int(eval(input()))
*S, = list(map(int, input().split()))

ans = 0
for a in range(1, N):
    d = 1
    while d*d <= N-1-a:
        if (N-1-a) % d == 0:
            if a > d and (a % d > 0 or N-1-a < a):
                k = (N-1-a) // d
                s = 0
                for i in range(k):
                    s += S[i*d+d] + S[i*d+a]
                ans = max(ans, s)
            e = (N-1-a) // d
            if a > e and (a % e > 0 or N-1-a < a):
                k = (N-1-a) // e
                s = 0
                for i in range(k):
                    s += S[i*e+e] + S[i*e+a]
                ans = max(ans, s)
        d += 1
print(ans)

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

ans = 0
for d in range(1, N):
    r = k = 0
    while k*d <= N-1:
        a = N-1-k*d
        if a <= d or (a <= k*d and a % d == 0):
            break
        r += S[N-1-k*d] + S[k*d]
        k += 1
        ans = max(ans, r)
print(ans)
# Original solution
import sys
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return eval(input())

def main():
    N = II()
    S = LI()
    ans = 0
    for C in range(1, N):
        tmp = 0
        L = 0
        lim = (N - 1 - C) if (N - 1) % C else (N // 2)
        while L < lim:
            tmp += S[L] + S[-1 - L]
            ans = max(ans, tmp)
            L += C
    return ans

print((main()))

# Optimized solution
import sys
sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def II(): return int(sys.stdin.readline())
def SI(): return eval(input())

def main():
    N = II()
    S = LI()
    S = S[:-1]
    ans = 0
    for C in range(1, N):
        tmp = 0
        L = 0
        lim = (N - 1 - C) if (N - 1) % C else (N // 2)
        while L < lim:
            tmp += S[L] + S[-L]
            ans = max(ans, tmp)
            L += C
    return ans

print((main()))
# Original solution
N = int(eval(input()))
s = list(map(int, input().split()))
ans = 0
for C in range(1,N):
    t = 0
    for x in range(C, N-1-C if (N-1)%C != 0 else N//2, C):
        t += s[x] + s[-x-1]
        ans = max(ans, t)
print(ans)

# Optimized solution
n,*s=list(map(int,open(0).read().split()));a=0
for i in range(1,n):
 t=0
 for j in range(0,[n//2,n+~i][(n-1)%i>0],i):t+=s[j]+s[~j];a=max(a,t)
print(a)
# Original solution
N = int(eval(input()))
s = [int(i) for i in input().split()]

ret = 0
for i in range(2, N - 1) :
    for j in range(1, i) :
        if (i % (i - j) == 0 and 2 * i < N) or (N - 1 - i) % (i - j) != 0 :
            continue
        
        ret = max(ret, sum(s[i::i-j]) + sum(s[i-j:-j-1:i-j]))

print((max(ret, 0)))

# Optimized solution
N = int(eval(input()))
s = [int(i) for i in input().split()]

ret = 0
for c in range(1, N) :
    k = 1
    tmp = 0
    flag = (N - 1) % c == 0
    while c * k < N - 1 :
        l = c * k
        r = N - 1 - l

        if (flag and r <= l) or r <= c:
            break

        tmp += s[l] + s[r]
        ret = max(ret, tmp)
        k += 1

print(ret)