Problem:


Score : 500 points

Problem Statement

There are N children standing in a line from left to right. The activeness of the i-th child from the left is A_i.

You can rearrange these children just one time in any order you like.

When a child who originally occupies the x-th position from the left in the line moves to the y-th position from the left, that child earns A_x \times |x-y| happiness points.

Find the maximum total happiness points the children can earn.

Constraints

2 \leq N \leq 2000

1 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

Print the maximum total happiness points the children can earn.

Sample Input 1

4
1 3 4 2

Sample Output 1

20

If we move the 1-st child from the left to the 3-rd position from the left, the 2-nd child to the 4-th position, the 3-rd child to the 1-st position, and the 4-th child to the 2-nd position, the children earns 1 \times |1-3|+3 \times |2-4|+4 \times |3-1|+2 \times |4-2|=20 happiness points in total.

Sample Input 2

6
5 5 6 1 1 1

Sample Output 2

58

Sample Input 3

6
8 6 9 1 2 1

Sample Output 3

85



Sample input:
4
1 3 4 2


Sample output:
20

Submission status: Wrong Answer

Solution code:
# -*- coding:utf-8 -*-
from collections import deque

class MyNumber():
    def __init__(self, a, i, N):
        self.distance = (N-1)/2 - i

def solve():
    N = int(input())
    As = list(map(int, input().split()))

    dic = {}
    for i, a in enumerate(As):
        if not a in dic:
            dic[a] = []
        dic[a].append(i)

    keys = list(dic.keys())
    keys.sort(reverse=True)

    update = False
    que = deque([i for i in range(0, N)])
    ans = 0
    for key in keys:
        cands = deque(dic[key])
        if len(cands) >= 2:
            update = True
        while len(cands) != 0:
            mni, mxi = cands[0], cands[-1]
            ret1_r, ret1_l = abs(que[-1]-mni), abs(que[0]-mni)
            ret2_r, ret2_l = abs(que[-1]-mxi), abs(que[0]-mxi)

            mx = max(ret1_r, ret1_l, ret2_r, ret2_l)
            ans += mx*key
            if mx == ret1_r:
                que.pop(), cands.popleft()
            elif mx == ret1_l:
                que.popleft(), cands.popleft()
            elif mx == ret2_r:
                que.pop(), cands.pop()
            else:
                que.popleft(), cands.pop()

    if update:
        ans += 1
    print(ans)





if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

Solution code:
from collections import deque
n = int(input())
li = list(map(int, input().split()))
complite = [0] * n #終了後のリスト
#両端から考えて行って、嬉しさが大きくなるように入れて行く決めて行く
i = 0 #i  : 何回目の操作かを考える
S = 0 #合計値の最大
right = n-1#右端
left = 0 #左端
while i < n:
    i += 1
    max_ = 0
    idoukyori = 0
    for j in range(n): #iは移動前の位置
        if max_ <= li[j] * abs(right-j):
            if idoukyori <= abs(right-j):
                idoumae = j
                idougo = right
                max_ = li[j] * abs(right-j)
            
    for j in range(n):
        if max_ <= li[j] * abs(j - left):
            if idoukyori <= abs(j - left):
                idoumae = j
                idougo = left
                max_ = li[j] * abs(j - left)
                
    
    #以上で移動前、移動後がわかる
    if idougo == left:
        left += 1
    else:
        right -= 1
    #移動前のリストは移動済みにしておく
    li[idoumae] = 0
    #合計値の計算
    S += max_
    
print(S)

Submission status: Wrong Answer

Solution code:
import itertools

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

all = list(itertools.permutations(A, N))

end = []
for pattern in all:
    answer = []
    count = N
    for i,value in enumerate(pattern):
        answer.append(value * (count - i))
        count -= 1
    end.append(sum(answer))

print(max(end))

Submission status: Wrong Answer

Solution code:
# -*- coding:utf-8 -*-
from collections import deque

class MyNumber():
    def __init__(self, a, i, N):
        self.distance = (N-1)/2 - i

def solve():
    N = int(input())
    As = list(map(int, input().split()))

    dic = {}
    for i, a in enumerate(As):
        if not a in dic:
            dic[a] = []
        dic[a].append(i)

    keys = list(dic.keys())
    keys.sort(reverse=True)

    update = False
    que = deque([i for i in range(0, N)])
    ans = 0
    for key in keys:
        cands = deque(dic[key])
        if len(cands) >= 1:
            update = True
        while len(cands) != 0:
            mni, mxi = cands[0], cands[-1]
            ret1_r, ret1_l = abs(que[-1]-mni), abs(que[0]-mni)
            ret2_r, ret2_l = abs(que[-1]-mxi), abs(que[0]-mxi)

            mx = max(ret1_r, ret1_l, ret2_r, ret2_l)
            ans += mx*key
            if mx == ret1_r:
                que.pop(), cands.popleft()
            elif mx == ret1_l:
                que.popleft(), cands.popleft()
            elif mx == ret2_r:
                que.pop(), cands.pop()
            else:
                que.popleft(), cands.pop()

    if update:
        ans += 1
    print(ans)





if __name__ == "__main__":
    solve()

Submission status: Wrong Answer

Solution code:
from heapq import heappush,heappop,heapify
from collections import deque,defaultdict,Counter
from itertools import permutations,combinations,groupby
import sys,bisect,string,math,time,functools,random
def Golf():*a,=map(int,open(0))
def I():return int(input())
def S_():return input()
def IS():return input().split()
def LS():return [i for i in input().split()]
def LI():return [int(i) for i in input().split()]
def LI_():return [int(i)-1 for i in input().split()]
def NI(n):return [int(input()) for i in range(n)]
def NI_(n):return [int(input())-1 for i in range(n)]
def StoLI():return [ord(i)-97 for i in input()]
def ItoS(n):return chr(n+97)
def LtoS(ls):return ''.join([chr(i+97) for i in ls])
def GI(V,E,Directed=False,index=0):
    org_inp=[];g=[[] for i in range(n)]
    for i in range(E):
        inp=LI();org_inp.append(inp)
        if index==0:inp[0]-=1;inp[1]-=1
        if len(inp)==2:
            a,b=inp;g[a].append(b)
            if not Directed:g[b].append(a)
        elif len(inp)==3:
            a,b,c=inp;aa=(inp[0],inp[2]);bb=(inp[1],inp[2]);g[a].append(bb)
            if not Directed:g[b].append(aa)
    return g,org_inp
def GGI(h,w,search=None,replacement_of_found='.',mp_def={'#':1,'.':0}):
#h,w,g,sg=GGI(h,w,search=['S','G'],replacement_of_found='.',mp_def={'#':1,'.':0}) # sample usage
    mp=[1]*(w+2);found={}
    for i in range(h):
        s=input()
        for char in search:
            if char in s:
                found[char]=((i+1)*(w+2)+s.index(char)+1)
                mp_def[char]=mp_def[replacement_of_found]
        mp+=[1]+[mp_def[j] for j in s]+[1]
    mp+=[1]*(w+2)
    return h+2,w+2,mp,found
def TI(n):return GI(n,n-1)
def bit_combination(k,n=2):
    rt=[]
    for tb in range(n**k):
        s=[tb//(n**bt)%n for bt in range(k)];rt+=[s]
    return rt
def show(*inp,end='\n'):
    if show_flg:print(*inp,end=end)

YN=['YES','NO'];Yn=['Yes','No']
mo=10**9+7
inf=float('inf')
l_alp=string.ascii_lowercase
#sys.setrecursionlimit(10**7)
input=lambda: sys.stdin.readline().rstrip()

class Comb:
    def __init__(self,n,mo=10**9+7):
        self.fac=[0]*(n+1)
        self.inv=[1]*(n+1)
        self.fac[0]=1
        self.fact(n)
        for i in range(1,n+1):
            self.fac[i]=i*self.fac[i-1]%mo
            self.inv[n]*=i
            self.inv[n]%=mo
        self.inv[n]=pow(self.inv[n],mo-2,mo)
        for i in range(1,n):
            self.inv[n-i]=self.inv[n-i+1]*(n-i+1)%mo
        return
    
    def fact(self,n):
        return self.fac[n]
        
    def invf(self,n):
        return self.inv[n]

    def comb(self,x,y):
        if y<0 or y>x:
            return 0
        return self.fac[x]*self.inv[x-y]*self.inv[y]%mo

show_flg=False
#show_flg=True

ans=0


n=I()
A=LI()
a=list(enumerate(A))
a.sort(key=lambda x:x[1])
show('a',a)

b=[[]for i in range(n)]
for i in range(n):
    for j in range(n):
        b[i].append(abs(i-j)*A[i])

for j in b:
    show('b',j)

l,r=0,n-1
rng=list(range(n))
skp=set()
for i in range(n):
    mx_l,mx_r=-1,-1
    for j in range(n):
        if j in skp:continue
        if b[j][l]>mx_l:
            mx_l=b[j][l]
            l_can=[(j,b[j][r])]
        elif b[j][l]==mx_l:
            l_can.append((j,b[j][r]))

        if b[j][r]>mx_r:
            mx_r=b[j][r]
            r_can=[(j,b[j][l])]
        elif b[j][r]==mx_r:
            r_can.append((j,b[j][l]))
    show('mx_l,mx_r',mx_l,mx_r)
    r_can.sort(key=lambda x:x[1])
    l_can.sort(key=lambda x:x[1])
    
    r_skp=r_can[0][0]
    l_skp=l_can[0][0]
    if r_skp>l_skp:
        ans+=b[r_skp][r]
        r-=1
        skp.add(r_skp)
        show('r')
    elif r_skp<l_skp:
        ans+=b[l_skp][l]
        l+=1
        skp.add(l_skp)
        show('l')
    else:
        if r_can[0][1]<l_can[0][1]:
            ans+=b[r_skp][r]
            r-=1
            skp.add(r_skp)
            show('r')
        else:
            ans+=b[l_skp][l]
            l+=1
            skp.add(l_skp)
            show('l')
        
        
        show('=')
    show(skp,(l,r),ans)

print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input().strip())
a = list(map(int, input().split()))
dic = {}
for i in range(len(a)):
    if dic.get(a[i]):
        dic[a[i]].append(i)
    else:
        dic[a[i]] = [i]
dic = sorted(dic.items(), reverse=True)
fo = n - 1
ba = 0
ans = 0
for elem in dic:
    val = elem[0]
    arr = elem[1]
    for idx in arr:
        if abs(fo - idx) < abs(ba - idx):
            ans += val * abs(ba - idx)
            ba += 1
        else:
            ans += val * abs(fo - idx)
            fo -= 1
print(ans)

Submission status: Wrong Answer

Solution code:
N = int(input())
A = list(map(int,input().split()))
out = 0
l = 0
r = N-1
while True:
    maxP1 = 0
    for i in range(N):
        P = A[i]*abs(l-i)
        if P > maxP1:
            maxA1 = A[i]
            maxP1 = P
            maxi1 = i
        if (P!=0)and(P == maxP1):
            if A[i]>maxA1:
                maxA1 = A[i]
                maxP1 = P
                maxi1 = i
    maxP2 = 0
    for i in range(N):
        P = A[i]*abs(r-i)
        if P > maxP2:
            maxA2 = A[i]
            maxP2 = P
            maxi2 = i
        if (P!=0)and(P == maxP2):
            if A[i]>maxA2:
                maxA2 = A[i]
                maxP2 = P
                maxi2 = i
    if maxP1 > maxP2:
        l+=1
        out += maxP1
        A[maxi1] = 0
    elif maxP1 < maxP2:
        r+=-1
        out += maxP2
        A[maxi2] = 0
    elif maxP1 == maxP2:
        if maxA1>maxA2:
            l+=1
            out += maxP1
            A[maxi1] = 0
        else:
            r+=-1
            out += maxP2
            A[maxi2] = 0
    if l==r:
        break

maxP3=0
for i in range(N):
    P = A[i]*abs(r-i)
    if P >= maxP3:
        maxP3 = P
        maxi3 = i
A[maxi3] = 0
out += maxP3

print(out)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys
from heapq import heappush, heappop
from numba import jit

class MinCostFlow:
    INF = 10**18

    def __init__(self, N):
        self.N = N
        self.G = [[] for i in range(N)]

    def add_edge(self, fr, to, cap, cost):
        G = self.G
        G[fr].append([to, cap, cost, len(G[to])])
        G[to].append([fr, 0, -cost, len(G[fr])-1])

    def flow(self, s, t, f):
        N = self.N; G = self.G
        INF = MinCostFlow.INF

        res = 0
        H = [0]*N
        prv_v = [0]*N
        prv_e = [0]*N

        while f:
            dist = [INF]*N
            dist[s] = 0
            que = [(0, s)]

            while que:
                c, v = heappop(que)
                if dist[v] < c:
                    continue
                for i, (w, cap, cost, _) in enumerate(G[v]):
                    if cap > 0 and dist[w] > dist[v] + cost + H[v] - H[w]:
                        dist[w] = r = dist[v] + cost + H[v] - H[w]
                        prv_v[w] = v; prv_e[w] = i
                        heappush(que, (r, w))
            if dist[t] == INF:
                return -1

            for i in range(N):
                H[i] += dist[i]

            d = f; v = t
            while v != s:
                d = min(d, G[prv_v[v]][prv_e[v]][1])
                v = prv_v[v]
            f -= d
            res += d * H[t]
            v = t
            while v != s:
                e = G[prv_v[v]][prv_e[v]]
                e[1] -= d
                G[v][e[3]][1] += d
                v = prv_v[v]
        return res

@jit
def solve(N: int, A: "List[int]"):
    flow = MinCostFlow(2*N+2)

    for i in range(N):
        for j in range(N):
            if i == j: continue
            flow.add_edge(i,j+N,1,-A[i]*abs(i-j))
    
    for j in range(N):
        flow.add_edge(2*N,j,1,0)
        flow.add_edge(j+N,2*N+1,1,0)

    print(-flow.flow(2*N,2*N+1,N))
    return


def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    A = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, A)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N=int(input())
A=list(map(int,input().split()))
L=[]
for i in range(N):
    L.append([A[i],i])

def counter(l):
    c=0
    for i in range(N):
        c+=L[i][0]*abs(L[i][1]-i)
    return c

point=0
for k in range(2):
    for i in range(N):
        for j in range(i+1,N)[::-1]:
            
            unchange=L[i][0]*abs(L[i][1]-i) + L[j][0]*abs(L[j][1]-j)
            change=L[i][0]*abs(L[i][1]-j) + L[j][0]*abs(L[j][1]-i)
            
            if change>unchange:
                L[i][0],L[j][0]=L[j][0],L[i][0]
                L[i][1],L[j][1]=L[j][1],L[i][1]

print(counter(L))

Submission status: Wrong Answer

Solution code:
n = int(input())
A = list(map(int, input().split()))
B = sorted(A, reverse=True)
x = 0
S = []
for i in range(n):
  S.append(i+1)

  T = []
for i in range(n):
  for j in range(n):
    if B[i]==A[j]:
      T.append(j+1)
      A[j] = 0

for i in range(n-1):
  a = S[0]
  b = S[-1]
  if T[i] > (a+b)/2:
    x += B[i]*(T[i]-a)
    S.remove(a)
  elif T[i] < (a+b)/2:
    x += B[i]*(b-T[i])
    S.remove(b)
  else:
    if T[i+1] > T[i]:
      x += B[i]*(b-T[i])
      S.remove(b)
    else:
      x += B[i]*(T[i]-a)
      S.remove(a)
y = x + T[-1]*S[0]
print(y)

Submission status: Wrong Answer

Solution code:
n = int(input())
A = list(map(int, input().split()))
dc = dict()
for i in range(n):
  for j in range(n):
    pt = A[i] * abs(i-j)
    if dc.get(pt) == None:
      dc[pt] = [(i,j)]
    else:
      dc[pt].append((i,j))
desc = sorted(dc.items(), key=lambda x: x[0], reverse=True)
ans = 0
xx = [0]*n
yy = [0]*n
for pt, xyarr in desc:
  for x,y in xyarr:
    if xx[x] == 0 and yy[y] == 0:
      ans += pt
      xx[x] = 1
      yy[y] = 1
print(ans)

Submission status: Wrong Answer

Solution code:
import math
import itertools

N = int(input())
A_map = map(int, input().split())
A = list(A_map)
NUM = [0]*N
for i in range(N):
    NUM[i] = i
a = list(itertools.permutations(A,N))
num = list(itertools.permutations(NUM,N))
ureshisa = 0
ureshisa_max = 0

for aa, nnum, i in zip(a, num ,range(len(a))):
    #print(aa)
    #print(nnum)
    #print(i)
    for j in range(N):
        ureshisa = ureshisa + aa[j]*abs(j-nnum[j])
    if ureshisa >= ureshisa_max:
        ureshisa_max = ureshisa
print(ureshisa_max)

Submission status: Wrong Answer

Solution code:
from collections import Counter
N = int(input())
A = list(map(int, input().split()))


def f(v):
    sorted_v = sorted(v)
    c = Counter(v)
    happy = 0
    for key in c.keys():
        v_idx = [n for n, i in enumerate(v) if i == key]
        sorted_v_idx = [n for n, i in enumerate(sorted_v) if i == key]
        move_idx = 0
        for i, j in zip(v_idx, sorted_v_idx):
            move_idx += j - i
        move_idx += (N - len(v)) * len(v_idx)
        happy += move_idx * key
    return happy


ans = 0
for i in range(max(N // 2 - 10, 0), min(N // 2 + 10, N)):
    l = A[:i]
    r = A[i:][::-1]
    # print('l, r', l, r, f(l), f(r))
    ans = max(ans, f(l) + f(r))
print(ans)

Submission status: Wrong Answer

Solution code:
def main():
    n = int(input())
    a = list(map(int, input().split()))
    b = [[i,x,0,0] for i,x in enumerate(a)]
    for i in b:
        i[2] = i[1] * i[0]
        i[3] = i[1] * (n-i[0])
    b.sort(key=lambda x:(x[2],x[3]),reverse=True)
    start = 0
    end = n-1
    ans = 0
    for i,k,p,s in b:
        if i - start > end - i:
            ans += (i-start)*k
            start += 1
        else:
            ans += (end-i)*k
            end -=1
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
N = int(input())
A = list(map(int,input().split()))
a = len(A)
output = 0
index = 0
m = 1
for i in range(1,a+1) :
    output +=  A[index] * abs(m-(a-0.45))
    index += 1
    m += 1
print(output)

Submission status: Wrong Answer

Solution code:
n = int(input())
activities = list(map(int,input().split()))

kids_list =[]

for i in range(n):
    kids_list.append([i, activities[i]]) 

left = 0
right = n-1

kids_list = sorted(kids_list, key = lambda x: x[1], reverse = True)
ans = 0
skip = 0

for i in range(n):
    target = kids_list[i][0]
    if target-left > right-target:
        ans += kids_list[i][1]*(target-left)
        left += 1
        if skip == 1:
            right -= 1
            skip = 0
    elif target-left < right-target:
        ans += kids_list[i][1]*(right-target)
        right -= 1
        if skip ==1:
            left +=1
            skip = 0
    else:
        ans += kids_list[i][1]*(right-target)
        if skip ==1:
            left += 1
            right -= 1
            skip = 0
        else:
            skip = 1

print(ans)

Submission status: Wrong Answer

Solution code:
import collections
import heapq
N = int(input())
A = list(map(int, input().split()))
B = [(A[i], i) for i in range(N)]
l = 0
r = N-1
ans = 0
for i in range(N):
    C = sorted(B, key=lambda x: x[0]*abs(x[1]-l))
    D = sorted(B, key=lambda x: x[0]*abs(x[1]-r))
    a, b = C.pop()
    c, d = D.pop()
    if a*abs(b-l) >= c*abs(d-r):
        ans += a*abs(b-l)
        B = list(C)
        l += 1
    else:
        ans += c*abs(d-r)
        B = list(D)
        r -= 1

print(ans)

Submission status: Wrong Answer

Solution code:
import sys
import math
from collections import deque
import heapq
MAX_INT = int(10e10)
MIN_INT = -MAX_INT
mod = 1000000007
sys.setrecursionlimit(1000000)
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

N = I()
a = IL()

start = [False]*(N+1)
visited = [False]*(N+1)

heappop = heapq.heappop
heappush = heapq.heappush
d = []

for i in range(N):
  for j in range(max(i, N-i-1) +1):
    if 0 <= i-j < N and 0 <= i+j < N:
      heappush(d, (-a[i]*j, i, [i-j, i+j])) # (score, st, ed)
    elif 0 <= i+j < N:
      heappush(d, (-a[i]*j, i, [i+j])) # (score, st, ed)
    elif 0 <= i-j < N:
      heappush(d, (-a[i]*j, i, [i-j])) # (score, st, ed)

ans = 0
while d:
  num,st,ed = heappop(d)
  if start[st] == False:
    if len(ed) == 1:
      if visited[ed[0]] == False:
        ans += num
        start[st] = True
        visited[ed[0]] = True
    else:
      for e in ed:
        if visited[e] == False:
          ans += num
          start[st] = True
          visited[e] = True
          break
print(-ans)

Submission status: Wrong Answer

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

l = []
for a in reversed(sorted(A)):
    idx = A.index(a)
    A[idx] = -1
    l.append((a,idx))

head, tail = 0, N-1

ans = 0
for tup in l:
    v = tup[0]
    idx = tup[1]

    if abs(idx - head) >= abs(idx - tail):
        ans += v * abs(idx-head)
        head += 1
    else:
        ans += v * abs(idx-tail)
        tail -= 1

print(ans)

Submission status: Wrong Answer

Solution code:
N=int(input())
A=[]
for i,a in enumerate(map(int,input().split())):
  A.append([a,i])
A=sorted(A,key=lambda x:x[0], reverse=True)
r,l=0,N-1
ans=0
i=0
while r<=l:
  _=[A[i]]
  i+=1
  while i<N and A[i][0]==_[0][0]:
    _.append(A[i])
    i+=1
  _=sorted(_,key=lambda x:x[1],reverse=True)
  k=-1
  for _k in range(len(_)):
    if k==-1:
      k=0
    else:
      k=len(_)-1-k
      if k<len(_)//2:
        k+=1    
    a,j=_[k]
    if (l+r)/2<j:
      ans+=a*(j-r)
      r+=1
    else:
      ans+=a*(l-j)
      l-=1
print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input().strip())
a = list(map(int, input().split()))
dic = {}
for i in range(len(a)):
    if dic.get(a[i]):
        dic[a[i]].append(i)
    else:
        dic[a[i]] = [i]
dic = sorted(dic.items(), reverse=True)
fo = n - 1
ba = 0
ans = 0
for elem in dic:
    print(elem)
    val = elem[0]
    arr = elem[1]
    for idx in arr:
        if abs(fo - idx) < abs(ba - idx):
            ans += val * abs(ba - idx)
            ba += 1
        else:
            ans += val * abs(fo - idx)
            fo -= 1
print(ans)

Submission status: Wrong Answer

Solution code:
import numpy as np

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

m = np.zeros((n, n))
for i in range(n):
    for j in range(n):
        m[i][j] = np.abs(i - j) * a[i]

row = np.sum(m, axis=0)
col = np.sum(m, axis=1)

_m = 2 * m - row[:, None] - col[None, :]

res = 0

for i in range(n):
    x, y = np.unravel_index(np.argmax(_m), _m.shape) 
    res += m[x][y]
    m[x, :] = 0
    m[:, y] = 0
    row = np.sum(m, axis=0)
    col = np.sum(m, axis=1)
    _m = 2 * m - row[:, None] - col[None, :]

print(int(res))

Submission status: Wrong Answer

Solution code:
n=int(input())
import numpy as np
a=list(map(int,input().split()))
l=[]
for i in range(n):
    l.append((a[i],i))
l.sort(reverse=True) 
left=0
right=n-1
ans=0
for i in l:
    if abs(right-i[1])==abs(i[1]-left):
        if n-1-right<=left:
            ans+=i[0]*abs(right-i[1])
            right-=1
            
        else:
            ans+=i[0]*abs(i[1]-left)
            left+=1
    elif abs(right-i[1])<abs(i[1]-left):
        ans+=i[0]*abs(i[1]-left)
        left+=1
    else:
        ans+=i[0]*abs(right-i[1])
        right-=1 
    
print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
a=list(map(int,input().split()))
y=n-1
x=0
s=0
for i in range(n):
    b=max(a)
    m=a.index(b)
    if abs(m-x)>abs(y-m):
        s+=b*abs(m-x)
        x+=1
    else:
        s+=b*abs(y-m)
        y-=1


    a.remove(b)
print(s)

Submission status: Wrong Answer

Solution code:
n = int(input())
a = list(map(int,input().split()))
ans = 0
p = []
for i in range(n):
    p.append([a[i],i])
lef = 0
rig = n-1
p.sort(reverse=True)

v = 0
for i in range(n//2):
    ans += max(p[2*i][0]*abs(p[2*i][1]-(lef+i)) + p[2*i+1][0]*abs(p[2*i+1][1]-(rig-i)),
    p[2*i][0]*abs(p[2*i][1]-(rig-i)) + p[2*i+1][0]*abs(p[2*i+1][1]-(lef+i)))
if n % 2 ==1:
    ans += p[n-1][0]*abs(p[n-1][1]-(-(-n//2)))

print(ans)

Submission status: Wrong Answer

Solution code:
n = int(input())
a = list(map(int, input().split()))
ans = 0
r_list = []
l_list = []
ag = []
for i in range(n):
    ag.append([a[i], i])
ag = sorted(ag)
for i in range(n):
    right = n - 1 - ag[i][1]
    left = ag[i][1]
    if right > left:
        ans += (right - len(r_list)) * ag[i][0]
        r_list.append(0)
    elif right < left:
        ans += (left - len(l_list)) * ag[i][0]
        l_list.append(0)
    elif len(r_list) < len(l_list):
        ans += (right - len(r_list)) * ag[i][0]
        r_list.append(0)
    else:
        ans += (left - len(l_list)) * ag[i][0]
        l_list.append(0)

print(ans)

Submission status: Wrong Answer

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

l = [[a[i]*max(i, n-1-i), a[i], i] for i in range(n)]
l.sort()

rmax = n-1
rmin = 0

happiness = 0
for i in range(n-1, -1, -1):
    if abs(l[i][2]-rmin) > abs(l[i][2]-rmax):
        happiness += l[i][1] * abs(l[i][2]-rmin)
        rmin += 1
    elif abs(l[i][2]-rmin) < abs(l[i][2]-rmax):
        happiness += l[i][1] * abs(l[i][2]-rmax)
        rmax -= 1
    else:
        if i == 0:
            happiness += l[i][1] * abs(l[i][2]-rmin)
        elif l[i-1][2] < l[i][2]:
            happiness += l[i][1] * abs(l[i][2]-rmin)
            rmin += 1
        else:
            happiness += l[i][1] * abs(l[i][2]-rmax)
            rmax -= 1    

print(happiness)

Submission status: Wrong Answer

Solution code:
n = input()
arr = [int(e) for e in input().split()]


upArr = []
downArr = []

i = 0
for i in range(len(arr)):
  tmp = (i,arr[i])
  upArr.append(tmp)
  downArr.append(tmp)
  i += 1

upArr.sort(key=lambda x: x[1])
downArr.sort(key=lambda x: x[1],reverse=True)

rl = n
ll = 0
ans = 0
for v in downArr:
  tmp = v[0] - int(n) + 1
  if tmp > v[0]:
    rl -= 1
    ans += tmp * v[1]
  else:
    ll += 1
    ans += v[0] * v[1]

print(ans)

Submission status: Wrong Answer

Solution code:
from collections import deque
n = int(input())
a = list(map(int, input().split()))
newa = []
for i, j in enumerate(a, 0):
    newa.append([i, j])
newa.sort(key=lambda x:x[1], reverse=True)
ans_list = deque(list(range(n)))
ans = 0
for index, value in newa:
    if abs(index-ans_list[0]) >= abs(index-ans_list[-1]):
        res = ans_list.popleft()
        ans += value*abs(index-res)
    else:
        res = ans_list.pop()
        ans += value*abs(index-res)
print(ans+2)

Submission status: Wrong Answer

Solution code:
N = int(input())
A = list(map(int,input().split()))
a = len(A)
output = 0
index = 0
m = 1
for i in range(1,a+1) :
    output +=  A[index] * abs(m-(a-0.4))
    index += 1
    m += 1
print(output)

Submission status: Wrong Answer

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

import heapq

q_left = []
for i in range(N):
    score = i * A[i]
    heapq.heappush(q_left, (-score, i, score))

q_right = []
for i in range(N):
    score = i * A[N - 1 - i]
    heapq.heappush(q_right, (-score, N - 1 - i, score))

ans = 0
used = [False] * N
for i in range(N):
    if i % 2 == 0:
        idx = i // 2
        while len(q_left) > 0:
            _, pos, score = heapq.heappop(q_left)
            if pos >= idx and used[pos] == False:
                ans += (score - A[pos] * idx)
                # print("#", i, pos, ans)
                break
        #
        used[pos] = True
    else:
        idx = N - 1 - i // 2
        while len(q_right) > 0:
            _, pos, score = heapq.heappop(q_right)
            if pos <= idx and used[pos] == False:
                ans += (score - A[pos] * (N - 1 - idx))
                # print("#", i, pos, ans)
                break
        #
        used[pos] = True

print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
c=list(map(int, input().split()))
a = [[] for i in range(n)]
for i in range(n):
    a[i].append(i)
    a[i].append(c[i])

dp=[0]*n
#i個目までをすべて移動させたときの最大値

yet=list(range(n))
#移動していないリスト

done=list(range(n))
#移動先あまりリスト

for i in range(n):
    tmp_yet=0
    tmp_done=0
    for j in yet:
        for k in done:
            tmp_dp=a[j][1]*abs(a[j][0]-k)
            if(tmp_dp>dp[i]):
                dp[i]=tmp_dp
                tmp_yet=j
                tmp_done=k
    if(i!=n-1):
        yet.remove(tmp_yet)
        done.remove(tmp_done)

print(sum(dp))

Submission status: Wrong Answer

Solution code:
N=int(input())
A=list(map(int,input().split()))
B=list(range(N))
Aleft=0
Aright=0
Aleftlist=[]
Arightlist=[]
Amax=0
Amaxmax=0
Apoint=0
Bpoint=0
check=0
for i in range(N):
  Amax=0
  Apoint=0
  Bpoint=0
  check=0
  for j in range((N-i)//2):
    if Amax<A[B[j]]*(N-i-j):
      Amax=A[B[j]]*(N-i-j)
      Apoint=B[j]
      Bpoint=j
  for j in range((N-i)//2,N-i):
    if Amax<A[B[j]]*j:
      Amax=A[B[j]]*j
      Apoint=B[j]
      Bpoint=0
      check=1
  Amaxmax+=Amax
  A[Apoint]=0
  del B[Bpoint]
  if check==0:
     Aleft+=1
  else:
     Aright+=1
print(Amaxmax)

Submission status: Wrong Answer

Solution code:
def main():
    n = int(input())
    active = [int(i) for i in input().split()]
    moved = [1 for _ in range(n)]
    visited = [1 for _ in range(n)]
    score = []
    for i, a in enumerate(active):
        for j in range(n):
            score.append((a * abs(i-j), a , i, j))
    score = sorted(score, key=lambda x: x[0] + 1/x[1], reverse=True)
    res = 0
    for sc in score:
        infant = sc[2]
        pos = sc[3]
        if visited[pos] and moved[infant]:
            res += sc[0]
            visited[pos] = 0
            moved[infant] = 0
    print(res)
    
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n=int(input())
import numpy as np
a=list(map(int,input().split()))
l=[]
for i in range(n):
    l.append((a[i],i))
l.sort(reverse=True) 
left=0
right=n-1
ans=0
for i in l:
    if abs(right-i[1])==abs(i[1]-left):
        if n-1-right<left:
            ans+=i[0]*abs(right-i[1])
            right-=1
            
        else:
            ans+=i[0]*abs(i[1]-left)
            left+=1
    elif abs(right-i[1])<abs(i[1]-left):
        ans+=i[0]*abs(i[1]-left)
        left+=1
    else:
        ans+=i[0]*abs(right-i[1])
        right-=1 
    
print(ans)

Submission status: Wrong Answer

Solution code:
n=int(input())
ls=list(map(int,input().split()))
d={}
for i in range(n):
    d[i]=ls[i]
start_i=0
end_i=n-1
sums=0
left_sum=0
right_sum=sum(ls)
for i in range(n):
    mx=0
    mx_pair=[]
    for idx,infant in d.items():
        if infant==-1:continue
        left_sum+=infant
        right_sum-=infant
        left, right = infant*(abs(idx-start_i)), infant*(abs(idx-end_i))
        if left>=mx:
            mx=left
            mx_pair=[idx,"left"]
        if right>=mx:
            mx=right
            mx_pair=[idx,"right"]
        if left==right and left>=mx:
            if left_sum>=right_sum:
                mx_pair=[idx,"left"]
            else:
                mx_pair=[idx,"right"]
    sums+=mx
    if mx_pair[1]=="left":
        start_i+=1
    elif mx_pair[1]=="right":
        end_i-=1
    d[mx_pair[0]]=-1
print(sums)

Submission status: Wrong Answer

Solution code:
N=int(input())
A=[int(i) for i in input().split(" ")]

children=[{"A":A[i],"x":i} for i in range(len(A))]
children.sort(key=lambda x:x["A"],reverse=True)

state=[{
    "rightEnd":N-1,
    "leftEnd":0,
    "grad":0
}]

for child in children:
    newState=[]
    for s in state:
        rightEnd=s["rightEnd"]
        leftEnd=s["leftEnd"]
        grad=s["grad"]
        rval=abs(rightEnd-child["x"])
        lval=abs(leftEnd-child["x"])
        if rval > lval:
            newState+=[{
                "rightEnd":rightEnd-1,
                "leftEnd":leftEnd,
                "grad":grad+rval*child["A"]
            }]
        elif rval < lval:
            newState+=[{
                "rightEnd":rightEnd,
                "leftEnd":leftEnd+1,
                "grad":grad+lval*child["A"]
            }]
        else:
            newState+=[{
                "rightEnd":rightEnd-1,
                "leftEnd":leftEnd,
                "grad":grad+rval*child["A"]
            }]
            newState+=[{
                "rightEnd":rightEnd,
                "leftEnd":leftEnd+1,
                "grad":grad+lval*child["A"]
            }]
    state=newState

state.sort(key=lambda x:x["grad"],reverse=True)
print(state[0]["grad"])