Problem:


Score: 500 points

Problem Statement

Given is a permutation P of \{1, 2, \ldots, N\}.

For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.

Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

Constraints

 2 \le N \le 10^5 

 1 \le P_i \le N 

 P_i \neq P_j  (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1 P_2 \ldots P_N

Output

Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

Sample Input 1

3
2 3 1

Sample Output 1

5

X_{1, 2} = 2, X_{1, 3} = 2, and X_{2, 3} = 1, so the sum is 2 + 2 + 1 = 5.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

30

Sample Input 3

8
8 2 7 3 4 5 6 1

Sample Output 3

136



Sample input:
3
2 3 1


Sample output:
5

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
import sys
from bisect import bisect_left, bisect_right
from operator import itemgetter
from fractions import gcd
from math import ceil, floor, sqrt
from copy import deepcopy
from collections import Counter, deque
import heapq
from functools import reduce
sys.setrecursionlimit(200000)
# local only
# if not __debug__:
#     fin = open('in_1.txt', 'r')
#     sys.stdin = fin
# local only
input = sys.stdin.readline
def ii(): return int(input())
def mi(): return map(int, input().rstrip().split())
def lmi(): return list(map(int, input().rstrip().split()))
def li(): return list(input().rstrip())
def debug(*args, sep=" ", end="\n"): print("debug:", *args, file=sys.stderr, sep=sep, end=end) if not __debug__ else None
def exit(*arg): print(*arg); sys.exit()
# template

class Avltree:
    """
    AVL木

    Methods
    -------
        search(x: int) -> Union(int)
            ◯.data == x のものが存在するある場合それを出力、ない場合 None を返す
        insert(x: int) -> None
            ◯.data == x がない場合 ◯.data == x なる頂点を作る。ある場合はなにもしない（上書きしない）
        y.to_s() -> int
            頂点yのdataを返す
        y.left_s() -> Union(int, key=None)
            頂点yのleftを返す(ない場合は key)
        search_lower(x: int, key_lower) -> int
            ○.data が x より小さいものの中で最も大きいものを出力、ない場合 key_lower を返す
        search_higher(x:int , key_higher) -> int
            ○.data が x より大きいものの中で最も小さいものを出力、ない場合 key_higher を返す
    """

    def __init__(self, key=None):
        self.key = key
        self.left = None
        self.right = None
        self.balance = "Even"
    def search(self, key):
        if self.key is None:
            return None
        if self.key > key:
            if self.left is None:
                return None
            else:
                return self.left.search(key)
        if self.key < key:
            if self.right is None:
                return None
            else:
                return self.right.search(key)
        return self  # self.key == keyの場合

    def search_lower(self, key, key_lower):
        if self.key is None:
            return key_lower
        if self.key > key:
            if self.left is None:
                return key_lower
            else:
                return self.left.search_lower(key, key_lower)
        if self.key < key:
            key_lower = self.key
            if self.right is None:
                return key_lower
            else:
                return self.right.search_lower(key, key_lower)
        # self.key == keyの場合
        if self.left is None:
            return key_lower
        else:
            if key_lower is None:
                return self.left.end_higher(self.left.key)
            else:
                return max(key_lower, self.left.end_higher(self.left.key))

    def search_higher(self, key, key_higher):
        if self.key is None:
            return key_higher
        if self.key > key:
            key_higher = self.key
            if self.left is None:
                return key_higher
            else:
                return self.left.search_higher(key, key_higher)
        if self.key < key:
            if self.right is None:
                return key_higher
            else:
                return self.right.search_higher(key, key_higher)
        # self.key == keyの場合
        if self.right is None:
            return key_higher
        else:
            if key_higher is None:
                return self.right.end_lower(self.right.key)
            else:
                return min(key_higher, self.right.end_lower(self.right.key))


    def end_lower(self, end_lower_key):
        if self.left is None:
            return end_lower_key
        else:
            end_lower_key = self.left.key
            return self.left.end_lower(end_lower_key)
    def end_higher(self, end_higher_key):
        if self.right is None:
            return end_higher_key
        else:
            end_higher_key = self.right.key
            return self.right.end_higher(end_higher_key)


    def DoubleRightRotation(self):
        tl = self.left
        self.left = tl.right.right
        tl.right.right = self  # selfはそのノード
        tlr = tl.right
        tl.right = tlr.left
        tlr.left = tl
        if tlr.balance == "Left":
            tlr.right.balance = "Right"
            tlr.left.balance = "Even"
        elif tlr.balance == "Right":
            tlr.right.balance = "Even"
            tlr.left.balance = "Left"
        elif tlr.balance == "Even":
            tlr.right.balance = "Even"
            tlr.left.balance = "Even"
        tlr.balance = "Even"
        return tlr
    def DoubleLeftRotation(self):
        tr = self.right
        self.right = tr.left.left
        tr.left.left = self
        trl = tr.left
        tr.left = trl.right
        trl.right = tr
        if trl.balance == "Right":
            trl.left.balance = "Left"
            trl.right.balance = "Even"
        elif trl.balance == "Left":
            trl.left.balance = "Even"
            trl.right.balance = "Right"
        elif trl.balance == "Even":
            trl.left.balance = "Even"
            trl.right.balance = "Even"
        trl.balance = "Even"
        return trl
    def SingleLeftRotation(self):
        tr = self.right
        tr.balance = "Even"
        self.balance = "Even"
        self.right = tr.left
        tr.left = self
        return tr
    def SingleRightRotation(self):
        tl = self.left
        tl.balance = "Even"
        self.balance = "Even"
        self.left = tl.right
        tl.right = self
        return tl
    def replace(self, p, v):  # 親ノードpの下にある自分(self)をvに置き換える。
        if p.left == self:
            p.left = v
        else:
            p.right = v
    def insert(self, key):  # rootでのみ呼ばれる挿入
        if self.key is None:  # rootを含むrotationはしないことにする。
            self.key = key
            return self
        if key < self.key:
            if self.left is None:
                self.left = Avltree(key)
            else:
                self.left.insertx(self, key)
        elif key > self.key:
            if self.right is None:
                self.right = Avltree(key)
            else:
                self.right.insertx(self, key)
        else:  # key == self.key:
            pass  # do not overwrite
    def insertx(self, p, key):  # replaceを呼ぶために一つ上の親を持っているinsert
        if self.key > key:
            if self.left is None:
                self.left = Avltree(key)
            else:
                if not self.left.insertx(self, key):  # 左の木が生長しなければ、
                    return False  # 成長しない
            if self.balance == "Right":
                self.balance = "Even"
                return False
            elif self.balance == "Even":
                self.balance = "Left"
                return True  # 成長した
            elif self.balance == "Left":
                if self.left.balance == "Right":
                    self.replace(p, self.DoubleRightRotation())
                elif self.left.balance == "Left":
                    self.replace(p, self.SingleRightRotation())
                return False  # rotationを行うと成長しない
        if self.key < key:
            if self.right is None:
                self.right = Avltree(key)
            else:
                if not self.right.insertx(self, key):
                    return False
            if self.balance == "Left":
                self.balance = "Even"
                return False
            elif self.balance == "Even":
                self.balance = "Right"
                return True
            elif self.balance == "Right":
                if self.right.balance == "Left":
                    self.replace(p, self.DoubleLeftRotation())
                elif self.right.balance == "Right":
                    self.replace(p, self.SingleLeftRotation())
                return False
        return False  # self.key == key の時は何もしないので成長もしない

    def to_s(self):
        return self.key
    def left_s(self):
        if self.left is None:
            return None
        return (self.left).key
    def right_s(self):
        if self.right is None:
            return None
        return (self.right).key

def main():
    N = ii()
    P = lmi()
    L = []
    for i in range(N):
        L.append((P[i], i))
    L.sort(reverse=True)
    // print(L)
    ans = 0
    rb = Avltree()
    for x, i in L:
        rb.insert(i)
        l1 = rb.search_lower(i, -1)
        l2 = rb.search_lower(l1, -1)
        r1 = rb.search_higher(i, N)
        r2 = rb.search_higher(r1, N)
        # print(l2, l1, r1, r2)
        ans += (abs(i - l1) * abs(r2 - r1) + abs(l1 - l2) * abs(r1 - i)) * x
    print(ans)
    return



if __name__ == '__main__':
    main()

Submission status: Runtime Error

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

import numpy as np
import heapq
my_list = np.array([])
P = np.array(P)
sum = 0
for i in range(N-1):
    for j in range(i+1, N):
        my_list = P[i:j+1]
        my_list = [-i for i in my_list]
        heapq.heapify(my_list)
        heapq.heappop(my_list)
        sum += -min(my_list)

print(sum)

Submission status: Runtime Error

Solution code:
class B():
    def __init__(self,N):
        self.N = N
        self.node = [0]*(self.N+1)
        self.cnt = 0

    def add(self,x): # 要素 x を追加
        self.cnt += 1
        while x <= self.N:
            self.node[x] += 1
            x += x & -x

    def delete(self,x): # 要素 x を削除
        self.cnt -= 1
        while x <= self.N:
            self.node[x] -= 1
            x += x & -x

    def count(self,x): # x以下の要素数
        tmp = 0
        while x > 0:
            tmp += self.node[x]
            x -= x & -x
        return tmp

    def get_max(self):
        return self.get_ith(self.cnt)

    def get_ith(self,i): # i 番目に小さい要素を取得
        NG = -1
        OK = self.N+1
        while OK-NG > 1:
            mid = (OK+NG)//2
            #print(OK,NG,self.count(mid))
            if self.count(mid) >= i:
                OK = mid
            else:
                NG = mid
        return OK

    def search_low(self,x): # x より小さい最大の要素
        xcn = self.count(x)
        NG = -1
        OK = x
        while OK-NG > 1:
            mid = (OK+NG)//2
            #print(OK,NG,self.count(mid))
            if self.count(mid) >= xcn:
                OK = mid
            else:
                NG = mid
        return OK

    def search_high(self,x): # x より大きい最小の要素
        xcn = self.count(x)
        NG = x
        OK = self.N + 1
        while OK-NG > 1:
            mid = (OK+NG)//2
            #print(OK,NG,self.count(mid))
            if self.count(mid) > xcn:
                OK = mid
            else:
                NG = mid
        return OK

import sys

stdin = sys.stdin

ni = lambda: int(ns())
nl = lambda: list(map(int, stdin.readline().split()))
nm = lambda: map(int, stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

n = ni()
p = nl()
q = [0]*(n+1)
for i in range(n):
    q[p[i]] = i+1
ans = 0
b = B(n)
b.add(q[-1])
for i in range(n-1,0,-1):
  v = q[i]
  l1 = b.search_low(v)
  r1 = b.search_high(v)
  l2 = b.search_low(l1)
  r2 = b.search_high(r1)
  ans += i*((r1-v)*(l1-l2) + (v-l1)*(r2-r1))
  b.add(v)
print(ans)

Submission status: Runtime Error

Solution code:
import bisect
def find_left(P,position):
    N=len(P)
    left1=[-1]*N
    left2=[-1]*N
    stack=[]
    popped=[[] for i in range(len(P))]
    stack=[P[0]]
    for i in range(1,len(P)):
        while stack:
            if stack[-1]<P[i]:
                
                popped[i]+=[stack.pop()]
            else:
                left1[i]=stack[-1]
                stack+=[P[i]]
                
                break
                
        if stack==[]:
            stack+=[P[i]]
            left1[i]=-1
        if left1[i]==-1:
            left2[i]==-1
        else:
            val=left1[i]
            pos=position[val]
            big_val_pos=len(popped[pos])
            if popped[pos]:
                big_val_pos=bisect.bisect_left(popped[pos],P[i])
                if big_val_pos<len(popped[pos]):
                    left2[i]=popped[pos][big_val_pos]
            
            #for x in popped[pos]:
            #    if x>P[i]:
            #        left2[i]=x
            #        break
                    
            
                    
            if left2[i]==-1:
                if len(stack)>=3:
                    left2[i]=stack[-3]
    return left1,left2


def find_right(P,position):
    right1,right2=find_left(P[::-1],position)
    return right1[::-1],right2[::-1]

P=list(map(int,input().strip().split(" ")))



N=len(P)
P=[p-1 for p in P]
position=[0]*len(P)
for i in range(len(P)):
    position[P[i]]=i

left1,left2=find_left(P,position)
right1,right2=find_right(P,position)

for i in range(N):
    if left1[i]!=-1:
        left1[i]=position[left1[i]]
    if left2[i]!=-1:
        left2[i]=position[left2[i]]
    
    if right1[i]==-1:
        right1[i]=N
    else:
        right1[i]=position[right1[i]]
    
    if right2[i]==-1:
        right2[i]=N
    else:
        right2[i]=position[right2[i]]
#print(P)
#print(left1,left2)
#print(right1,right2)

ans=0
for i in range(N):
    L1,L2,R1,R2=left1[i],left2[i],right1[i],right2[i]
    val=P[i]+1
    if val==N:
        continue
    temp=0
    if L1==-1:
        temp+=(i+1)*(R2-R1)
    elif R1==N:
        temp+=(L1-L2)*(N-i)
    else:
        temp+=(L1-L2)*(R1-i)
        temp+=(i-L1)*(R2-R1)
    ans+=temp*val
print(ans)

Submission status: Runtime Error

Solution code:
import bisect
 
n = int(input())
P = list(map(int, input().split(" ")))
index = sorted(range(len(P)), key=lambda k: P[k], reverse=True)
bi = []
bisect.insort(bi,P.index[0])
C = 0
lc = 0
rc = 0
C1 = 0
for i in index[1:]:
  #bisect.insort(bi,i)
  l = bisect.bisect_left(bi,i)
  if l == 0:
    lc = i + 1
    if len(bi) == 1:
      rc = n - bi[0]
    else:
      rc = bi[l+1] - bi[l]
    C1 = lc*rc
  elif l == len(bi):
    if len(bi) == 1:
      lc = bi[0] + 1
    else:
      lc = bi[l-1] - bi[l-2]
    rc = n - i
    C1 = lc*rc
  else: 
    if len(bi) == 2:
      lc = bi[0] + 1
      rc = bi[1] - i
      C1 = lc*rc
      lc = i - bi[0]
      rc = n - bi[1]
      C1 += lc*rc
    elif l == 1:
      lc = bi[0] + 1
      rc = bi[1] - i
      C1 = lc*rc
      lc = i - bi[0]
      rc = bi[2] - bi[1]
      C1 += lc*rc
    elif l == len(bi) - 1:
      lc = bi[l-1] - bi[l-2]
      rc = bi[l] - i
      C1 = lc*rc
      lc = i - bi[l-1]
      rc = n - bi[l]
      C1 += lc*rc
    else:
      lc = bi[l-1] - bi[l-2]
      rc = bi[l] - i
      C1 = lc*rc
      lc = i - bi[l-1]
      rc = bi[l+1] - bi[l]
      C1 += lc*rc
  C += (P[i]*C1)
  bisect.insort(bi,i)
  
print(C)

Submission status: Runtime Error

Solution code:
N = int(input())
c = list(map(int, input().split(" ")))
V = []
cnt = [0]
def dfs(s):
  #print(V)
  if len(s)==2:
    return min(s)
  b = dfs(s[:-1])
  a = dfs(s[1:])
  
  if s[:-1] not in V:
    cnt[0] += b
  
  if s[1:] not in V:
    cnt[0] += a
  
  V.append(s[1:])
  V.append(s[:-1])
  if a==b and a<s[0]:
    return min(s[0],s[-1])
  else:
    return max(a,b)
t = dfs(c)
print(cnt[0]+t)

Submission status: Runtime Error

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

dp = [0]*N
first = P[0]
second = 0
print(first, second)

ans = 0
for i in range(1, N):
    if P[i] > first:
        dp[i] = dp[i-1]+(first-second)*(i-1)+min(P[i-1], P[i])
        first, second = P[i], first
    elif P[i] > second:
        dp[i] = dp[i-1]+(P[i]-second)*(i-1)+min(P[i-1], P[i])
        second = P[i]
    else:
        dp[i] = dp[i-1]+min(P[i-1], P[i])

    if i >= 3:
        if P[i] == max(P[i-2], P[i-1], P[i]):
            

    ans += dp[i]

    print(i, P[i], dp[i], first, second, ans, dp)

print(ans)

Submission status: Runtime Error

Solution code:
n = int(input())
p = list(map(int, input().split()))
s = 0
for i in range(n - 1):
    l = n
    while i + 1 != l:
        count += 1
        no1 = max(p[i: l])
        no2 = sorted(p[i: l])[-2]
        a = p.index(no1)
        b = p.index(no2)
        if p[i: l] == sorted(p[i: l]):
            s += sum(p[i: l - 1])
            break
        if a < b:
            s += (l - b) * no2
            l = b
        else:
            s += (l - a) * no2
            l = a
print(s)

Submission status: Runtime Error

Solution code:
import sys
import bisect

sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI(): return list(map(int, sys.stdin.readline().split()))
def II(): return int(sys.stdin.readline())
def LS(): return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]

def main():
    n = II()
    p_s = LI()
    indexs = [0 for i in range(n+1)]
    for i in range(n):
        indexs[p_s[i]] = i
    A = [-1, -1, n, n]
    ans = 0
    for i in range(n):
        ind = indexs[n - i]
        index = bisect.bisect_right(A, ind)
        A.insert(ind)
        ans += (A[index-1] - A[index-2]) * (A[index+1] - A[index]) * (n-i)
        ans += (A[index+2] - A[index+1]) * (A[index] - A[index-1]) * (n-i)
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
import bisect

sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI(): return list(map(int, sys.stdin.readline().split()))
def II(): return int(sys.stdin.readline())
def LS(): return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]

def main():
    n = II()
    p_s = LI()
    indexs = [0 for i in range(n+1)]
    for i in range(n):
        indexs[p_s[i]] = i
    A = [-1, -1, n, n]
    ans = 0
    for i in range(n):
        ind = indexs[n - i]
        index = bisect.bisect_right(A, ind)
        A.insert(index)
        ans += (A[index-1] - A[index-2]) * (A[index+1] - A[index]) * (n-i)
        ans += (A[index+2] - A[index+1]) * (A[index] - A[index-1]) * (n-i)
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import sys
import bisect

sys.setrecursionlimit(10**7)
INF = 10 ** 18
MOD = 10 ** 9 + 7
def LI(): return list(map(int, sys.stdin.readline().split()))
def II(): return int(sys.stdin.readline())
def LS(): return list(map(list, sys.stdin.readline().split()))
def S(): return list(sys.stdin.readline())[:-1]

def main():
    n = II()
    p_s = LI()
    indexs = [0 for i in range(n+1)]
    for i in range(n):
        indexs[p_s[i]] = i
    A = [-1, -1, n, n]
    ans = 0
    for i in range(n):
        ind = indexs[n - i]
        index = bisect.bisect_right(A, ind)
        bisect.insert(A, ind)
        ans += (A[index-1] - A[index-2]) * (A[index+1] - A[index]) * (n-i)
        ans += (A[index+2] - A[index+1]) * (A[index] - A[index-1]) * (n-i)
    print(ans)

if __name__ == '__main__':
    main()

Submission status: Runtime Error

Solution code:
import bisect
n=int(input())
p=list(map(int,input().split()))

q=[]
for i in range(n):
    q.append((i,p[i]))
q.sort(key=lambda x:x[1],reverse=True)
a=[]
a.append(q[0])
a.append(q[1])
a.sort()
ans=0
ans+=(a[0][0]+1)*(n-a[1][0])*q[1][1]
#print(ans,a)
for i in range(2,n):
    idx=bisect.bisect_left(a,q[i])
    #print(idx,a)
    if idx==0:
        buf=(q[i][0]+1)*(a[1][0]-a[0][0])*q[i][1]
    elif idx==i:
        buf=(n-q[i][0])*(a[i-1][0]-a[i-2][0])*q[i][1]
    elif idx==1:
        buf=((a[idx][0]-q[i][0])*(a[idx-1][0]+1)+(q[i][0]-a[idx-1][0])*(a[idx+1][0]-a[idx][0]))*q[i][1]
    elif idx==i-1:
        buf=((a[idx][0]-q[i][0])*(a[idx-1][0]-a[idx-2][0])+(q[i][0]-a[idx-1][0])*(n-a[idx][0]))*q[i][1]
    else:
        buf=((a[idx][0]-q[i][0])*(a[idx-1][0]-a[idx-2][0])+(q[i][0]-a[idx-1][0])*(a[idx+1][0]-a[idx][0]))*q[i][1]
    ans+=buf
    #print(buf,a)
    a.insert(idx,q[i])
print(ans)

Submission status: Runtime Error

Solution code:

def main():

    from bisect import *
    N = int(input())
    P = list(map(int, input().split()))

    index = [-1]*N
    for i in range(N):
        index[P[i]-1] = i


    q = [-1, -1, index[-1], N, N]
    ans = 0
    for i in range(N-1):
        ind = index[-2-i]
        insertion = bisect_left(q, ind)
        ans += ((q[insertion+1]-q[insertion])*(ind-q[insertion-1]) + (q[insertion]-ind)*(q[insertion-1]-q[insertion-2])) * (N-1-i)
        q.insert(insertion, ind)

    print(ans)

if __name__ == "__main__":
    main()

Submission status: Runtime Error

Solution code:

def fs(Q,n):
    l = len(Q) - 1
    res = 0
    for i in range(n + 2):
        res += Q[l - i]
        if res == 2:
            return l - i + 1
def main():
    N = int(input())
    B = list(map(int,input().split()))
    Q = [1] * N
    s = N - 1
    res = N - 1
    for i in range(N - 2):
        Q[B[i]] = 0
        s = fs(Q,i)
        res += s
    s = N - 1
    for i in range(N - 3 ,0,-1):
        Q[B[i]] = 0
        s = fs(Q,i)
        res += s
    print(res)

        
        

if __name__ == "__main__":
    
    main()

Submission status: Runtime Error

Solution code:
N=int(input())
t=list(map(lambda x:[int(x),1],input().split()))

cnt=0
ans=0
while t!=[]:
	s=[]
	cnt+=1
	for i in range(1,len(t)):
		u=list(set([*t[i-1], *t[i]]))
		u.sort(reverse=True)
		s.append(u[:2])
	for j in s:
		ans+=j[1]
	t=s
print(ans)

Submission status: Runtime Error

Solution code:
# coding: utf-8
# Your code here!

import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline #文字列入力のときは注意

n = int(input())
a = [int(i) for i in readline().split()]
a.sort(reverse=True)


from collections import deque

def check(i,x):
    c = i.bit_length()-1
    if x < res[i^(1<<c)]:
        return True
    return False

N = 1<<n
res = [0]*N
res[0] = a[0]

def dame(i):
    if not sub: return False
    c = i.bit_length()-1
    i ^= (1<<c)
    if i == sub[0]: return True
    else: return False


q = deque(range(1,N+1))
sub = deque()

for i,ai in enumerate(a):
#    print(q)
#    print(sub)
#    print(i,ai)
#    print(res)
    if i == 0: continue

    if sub and check(sub[0],ai):
        res[sub[0]]=ai
        sub.popleft()
    else:
        while q and not check(q[0],ai):
            ii = q.popleft()
            if dame(ii):
                print("No"); exit()
            sub.append(ii)
        ii = q.popleft()
#        print(ii,sub)
        if dame(ii):
            print("No"); exit()
        if ii == N: 
            print("No"); exit()
        res[ii] = ai
    
    
    
if q: print("Yes")
else: print("No")

Submission status: Runtime Error

Solution code:
def A():
    print(int(input())**3)

def B():
    N = int(input())
    A = [int(i) for i in input().split()]
    B = [int(i) for i in input().split()]
    C = [int(i) for i in input().split()]

    points = B[A[0]-1]
    previous = A[0]-1
    #print(points)
    for i in range(1, N):
        points += B[A[i]-1]
        if A[i]-1 == previous+1:
            points += C[previous]
        #print(points)
        previous = A[i]-1
    
    print(points)

def C():
    N = int(input())
    B = [int(i) for i in input().split()]

    s = B[0]
    temp = B[0]
    for i in range(1, len(B)):
        if B[i] > temp:
            s += temp
        else:
            s += B[i]
        
        temp = B[i]
    
    s += temp

    print(s)

def E():
    N = int(input())
    P = [int(i) for i in input().split()]
    s = 0
    q = {}
    for i in range(N):
        q[P[i]] = i
    for i in range(N-1):
        for j in range(i+1, N):
            temp = P[i:j+1]
            del temp[q[max(temp)]]
            m = max(temp)
            s += m
            if m == N-1:
                #print("s")
                s += m*(N-(j+1))
                break

            #print(i, j, max(temp), temp)

    print(s)

E()

Submission status: Runtime Error

Solution code:
 = int(input())
P = list(sorted(list(map(int, input().split()))))

def s(P, n):
    return (n-1)*P[n]

sum = 0
for i in range(N-1, -1, -1):
    sum += s(P, i)


print(sum+P[N-1])

Submission status: Runtime Error

Solution code:
N, K = map(int, input().split())
S = input()

T = [-1]
i, F, P = 0, 0, 0
while i < N-1:
  if S[i] != S[i+1]:
    T.append(i)
T.append(N-1)
Q = []
if len(T) > 2:
  for j in range(len(T)-2):
  	Q.append(T[j+2]-T[j])
else:
  Q.append(N)
Ki = 0
Si = 0
while len(Q) == 0 or Ki < N:
  Si += max(Q)
  Q.remove(max(Q))
  
print(Si)

Submission status: Runtime Error

Solution code:
n=int(input())
p=list(map(int,input().split()))
c=0
for i in range(n):
    if p[i]!=n:
        a,b=[-1,-1],[n,n]
        t=i+1
        g=0
        while t<n and g!=2:
            if p[i]<p[t]:
                b[g]=t
                g+=1
            t+=1
        t=i-1
        g=0
        while t>-1 and g!=2:
            if p[i]<p[t]:
                b[g]=t
                g+=1
            t+=1
        c+=p[i]*(a[0]*b[1]+a[1]*b[0]-2*a[0]*b[0])
print(c)

Submission status: Runtime Error

Solution code:
def A():
    print(int(input())**3)

def B():
    N = int(input())
    A = [int(i) for i in input().split()]
    B = [int(i) for i in input().split()]
    C = [int(i) for i in input().split()]

    points = B[A[0]-1]
    previous = A[0]-1
    #print(points)
    for i in range(1, N):
        points += B[A[i]-1]
        if A[i]-1 == previous+1:
            points += C[previous]
        #print(points)
        previous = A[i]-1
    
    print(points)

def C():
    N = int(input())
    B = [int(i) for i in input().split()]

    s = B[0]
    temp = B[0]
    for i in range(1, len(B)):
        if B[i] > temp:
            s += temp
        else:
            s += B[i]
        
        temp = B[i]
    
    s += temp

    print(s)

def E():
    N = int(input())
    P = [int(i) for i in input().split()]
    s = 0
    q = {}
    for i in range(N):
        q[P[i]] = i
    for i in range(N-1):
        for j in range(i+1, N):
            temp = P[i:j+1]
            del temp[q[max(temp)]]
            m = max(temp)
            s += m
            if m == N-1:
                #print("s")
                s += m*(N-(j+1))
                break

            print(i, j, max(temp), temp)

    print(s)

E()

Submission status: Runtime Error

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

ans = 0
list = list()
for l in range(N-1):
    r=l+2
    while r <=N:
        
        list.extend(P[l:r])
        print(list)
        #ソートA[0]<A[1]<...
        list.sort(reverse=True)
        ans +=list[1]
        list.clear()
        r+=1
print(ans)

Submission status: Runtime Error

Solution code:

def fs(Q,n):
    l = len(Q) - 1
    res = 0
    for i in range(n + 2):
        res += Q[l - i]
        if res == 2:
            return l - i + 1
def main():
    N = int(input())
    B = list(map(int,input().split()))
    Q = [1] * N
    s = N - 1
    res = N - 1
    for i in range(N - 2):
        Q[i] = 0
        s = fs(Q,i)
        res += s
    s = N - 1
    for i in range(N - 3 ,0,-1):
        Q[i] = 0
        s = fs(Q,i)
        res += s
print(res)

        
        

if __name__ == "__main__":
    
    main()

Submission status: Runtime Error

Solution code:
import cython

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

cnt = 0
for l in range(n-1):
  for r in range(n -l -1):
    lst = p[l : l + r + 2]
    cnt += sorted(lst)[-2]

print(cnt)

Submission status: Runtime Error

Solution code:
#! /Library/Frameworks/Python.framework/Versions/3.7/bin/python3
N = int(input())
P = list(map(int, input().split()))
s = 0
for i in range(N):
    count = 0
    a1 = i
    a2 = i
    a3 = i
    a4 = i
    while a2 > 0:
        a2 -= 1
        if (P[i] < P[a2]):
            a1 = a2
            if a1 == 0:
                count = 1
            else:
                while a1 > 0:
                    a1 -= 1
                    if (P[i] < P[a1]):
                    count += (a2 - a1)
    while a3 < N-1:
        a3 += 1
        if (P[i] < P[a3]):
            a4 = a3
            if a4 == 0:
                count = 1
            else:
                while a4 > 0:
                    a4 += 1
                    if (P[i] < P[a4]):
                    count += (a4 - a3)
    sum += P[i] * count
print(str(sum))

Submission status: Runtime Error

Solution code:
N = int(input())

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

ans = 0

for i in range(N-1):
  for j in range(i+1,N):
    sub = P[i:j].sorted()
    ans += sub[j-i]
  
print(ans)

Submission status: Runtime Error

Solution code:
N = int(input())
P = list(map(int,input().split()))
def main():
    ans = 0
    left = 0
    while left < N - 1:
        count = 0
        sec = min(P[left],[left + 1])
        for i in range(left,N):
            count += 1
            if P[i] > sec:
                ans += sec*count
                left += 1
                break
    print(ans)
    return
main()

Submission status: Runtime Error

Solution code:
n = int(input())
p = [int(i) for i in input().split()]
ans = 0
for i in range(n): #左端から
  if i==0: #一番左なら
    if p[i]==n:
      ans += 0
    elif p[i]==n-1:
      idx = p.index(n)
      ans += p[i]*(n-idx)
    else:
      idx = []
      for j in reversed(range(p[i]+1,n+1)):
        idx.append(p.index(j))
      idx.sort()
      temp = idx[1]-idx[0]
      ans += p[i]*temp
  elif i==n-1: #右端なら
    if p[i]==n:
      ans += 0
    elif p[i]==n-1:
      idx = p.index(n)
      ans += p[i]*(idx+1)
    else:
      idx = []
      for j in reversed(range(p[i]+1,n+1)):
        idx.append(p.index(j))
      idx.sort()
      temp = idx[-1] - idx[-2]
      ans += p[i]*temp
  else: #真ん中なら
    if p[i]==n:
      ans+=0
    elif p[i]==n-1:
      idx = p.index(n)
      chi = min(i,idx)
      ook = max(i,idx)
      temp = (chi+1)*(n-ook)
      ans += p[i]*temp
    else: #「大」が2つ以上あるとき
      left = p[:i]
      right = p[i+1:]
      if max(left)<p[i]: #小●大
        idx = []
        for j in range(i+1,n):
          if p[j]>p[i] and (len(idx)<2):
            idx.append(j)
          elif len(idx)==2:
            break
          else:
            idx = idx
        temp = (i+1)*(idx[1]-idx[0])
        ans += p[i]*temp
      elif max(right)>p[i]: #大●小
        idx = []
        for j in reversed(range(i)):
          if p[j]>p[i] and (len(idx)<2):
            idx.append(j)
          elif len(idx)==2:
            break
          else:
            idx = idx
        temp = (n-i)*(idx[0]-idx[1])
        ans += temp*p[i]
      else:
        idx_left = []
        for k in reversed(range(i)):
          if p[k]>p[i] and (len(idx_left)<2):
            idx_left.append(k)
          elif len(idx_left)==2:
            break
          else:
            idx_left = idx_left
        if len(idx_left)<2:
          idx_left.append(-1)
        idx_right = []
        for l in range(i+1,n):
          if p[l]>p[i] and (len(idx_right)<2):
            idx_right.append(l)
          elif len(idx_right)==2:
            break
          else:
            idx_right = idx_right
        if len(idx_right)<2:
          idx_right.append(n)
        temp_left = (idx_right[0]-i)*(idx_left[0]-idx_left[1])
        temp_right = (idx_right[1]-idx_right[0])*(i-idx_left[0])
        temp = temp_left+temp_right
        ans += p[i]*temp
print(ans)