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: Wrong Answer

Solution code:
import sys
# input関係の定義
sys.setrecursionlimit(200000)
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
# template


# BEGIN CUT HERE
class BIT:
    '''
    BinaryIndexedTreeのクラス。0-indexed に統一してあるので0からn-1までの配列と思って使える。

    Parameters
    ----------
        n (Union(int, list)): int なら使う BIT のサイズ。list ならそのlistで BIT を初期化する
    '''

    def __init__(self, x, d=0):
        if isinstance(x, int):
            self.size = x
            self.tree = [d for _ in range(self.size + 1)]
        elif isinstance(x, list):
            self.size = len(x)
            self.tree = [d for _ in range(self.size + 1)]
            self.build(x)
        else:
            raise TypeError

    def build(self, arr):
        """
        初期化されたあとのBITをリストの値に設定する

        Parameters
        ----------
            arr (list): 元のlsit

        Raises
        ------
            TypeError: 入力はlistでないといけないことに注意してください。
        """
        if not isinstance(arr, list):
            raise TypeError
        for num, x in enumerate(arr):
            self.add(num, x)

    def sum(self, i):
        '''[0,i] の和'''
        s = self.tree[0]
        while i > 0:
            s += self.tree[i]
            i -= (i & -i)
        return s

    def add(self, i, a):
        i += 1
        '''i番目の要素にaを足す'''
        if(i == 0):
            return
        while (i <= self.size):
            self.tree[i] += a
            i += (i & -i)

    def lower_bound(self, w):
        '''[0,i]の和 >= w をみたす最小の index
        Examples
        ----------
        >>> bit = BIT([1,0,0,1,0,1,0])
        >>> bit.lower_bound(1)
        0
        >>> bit.lower_bound(2)
        3
        >>> bit.lower_bound(3)
        5
        '''
        if w <= 0:
            return 0
        x = 0
        k = 1 << (self.size.bit_length() - 1)
        while k:
            if x + k <= self.size and self.tree[x + k] < w:
                w -= self.tree[x + k]
                x += k
            k //= 2
        return x

    def getKthNum(self, w):
        '''k番目(k = 0, 1, ...)に小さい数を返す'''
        w += 1
        if w <= 0:
            return 0
        x = 0
        k = 1 << (self.size.bit_length() - 1)
        while k > 0:
            if x + k <= self.size and self.tree[x + k] < w:
                w -= self.tree[x + k]
                x += k
            k //= 2
        return x


    def upper_bound(self, w):
        w += 0.00000000001
        return self.lower_bound(w)

    def query(self, l, r):
        '''[l, r)の和を求める'''
        return self.sum(r) - self.sum(l)

    # 出力関係（デバッグのみに用いる）
    def __getitem__(self, item):
        if not isinstance(item, int):
            _tmp = item.indices(self.size + 1)
            return [self.sum(i + 1) - self.sum(i) for i in range(_tmp[0], _tmp[1], _tmp[2])]
        else:
            return self.sum(item + 1) - self.sum(item)
    def __str__(self):
        return str(self[0:self.size])

# END CUT HERE

# BEGIN CUT HERE
def compress(v):
    sort_v = list(set(v))
    sort_v.sort()
    return sort_v
def dictionary(v):
    res = dict()
    for i in range(len(v)):
        res[v[i]] = i
    return res
# END CUT HERE


def AOJ_ALDS_1_5_D():
    """https://onlinejudge.u-aizu.ac.jp/courses/lesson/1/ALDS1/5/ALDS1_5_D"""
    n = ii()
    a = lmi()
    bit = BIT(n)
    ans = 0
    mp = dictionary(compress(a))
    for j in range(n):
        ans += j - bit.sum0(mp[a[j]])
        bit.add0(a[j], 1)
    print(ans)
# verified on 2019/06/13


def AOJ_DSL2B():
    """https://onlinejudge.u-aizu.ac.jp/courses/library/3/DSL/2/DSL_2_B"""
    n, q = mi()
    bit = BIT(n, 0)
    for _ in range(q):
        c, x, y = mi()
        if c == 0:
            bit.add(x, y)
        elif c == 1:
            print(bit.query(x, y + 1))
# verified on 2019/06/13


def ARC033_C():
    q = ii()
    bit = BIT(200000, 0)
    for _ in range(q):
        t, x = mi()
        if t == 1:
            bit.add(x, 1)
        elif t == 2:
            k = bit.lower_bound(x)
            bit.add(k, -1)
            print(k)
# verified on 2019/06/13
# https://atcoder.jp/contests/arc033/tasks/arc033_3
# pypy3:558ms https://atcoder.jp/contests/arc033/submissions/5896367
# Python3:1966ms https://atcoder.jp/contests/arc033/submissions/5896359

def ABC140_E():
    '''https://atcoder.jp/contests/abc140/tasks/abc140_e'''
    N = ii()
    P = lmi()
    L = [0 for i in range(N)]
    for i in range(N):
        L[P[i] - 1] = i
    L.reverse()
    ans = 0
    bit = BIT(N)
    for num, i in enumerate(L):
        bit.add(i, 1)
        # print(bit)
        x = bit.sum(i)
        l2 = bit.getKthNum(x - 1)
        l1 = bit.getKthNum(x)
        r1 = bit.getKthNum(x + 1)
        r2 = bit.getKthNum(x + 2)
        debug(x, l2, l1, r1, r2)
        ans += (abs(r2 - r1) * abs(i - l1) + abs(l1 - l2) * abs(r1 - i)) * (N - num)
    print(ans)


if __name__ == '__main__':
    import doctest
    doctest.testmod()
    # AOJ_ALDS_1_5_D()
    # AOJ_DSL2B()
    # ARC033_C()
    ABC140_E()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
n=int(input())
p=list(map(int,input().split()))
p.sort(reverse=True)
ans=0
for i in range(n):
    data=[-1]*2+[n]*2
    now=p[i]
    for j in range(i-1,-1,-1):
        if p[j]>now:
            if data[1] == -1:
                data[1]=j
            else:
                data[0]=j
                break
    for j in range(i+1,n):
        if p[j]>now:
            if data[2] == n:
                data[2]=j
            else:
                data[3]=j
                break

    ans+=((data[1]-data[0])*(data[2]-i)+(data[3]-data[2])*(i-data[1]))*now  
print(ans)

Submission status: Wrong Answer

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

Total = 0
MaxValue = 0
SecondValue = 0
AddCount = 0
for i in range(N-1):
    if MaxValue == 0 or SecondValue == 0 or (MaxValue > 0 and MaxValue == P[i-1]) or (SecondValue > 0 and SecondValue == P[i-1]):
        #再計算
        MaxValue    = max(P[i], P[i+1])
        SecondValue = min(P[i], P[i+1])
        AddCount = SecondValue
    else:
        AddCount = AddCount - P[i-1]
        Total = Total + AddCount
        continue

    for j in range(i+2, N):
        v = P[j]
        if v > MaxValue:
            SecondValue = MaxValue
            MaxValue = v
        elif v > SecondValue:
            SecondValue = v
        AddCount = AddCount + SecondValue
    Total = Total + AddCount

print(Total)

Submission status: Wrong Answer

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

index = [0] * (n+1)

for i in range(n):
    index[p[i]] = i

used = set()
result = 0
for i in range(1, n+1)[::-1]:
    x = index[i]
    poss = list(used)
    if len(poss) == 0:
        used.add(x)
        continue
    dx = bisect.bisect_left(poss, x)
    # 左に１番目の数がある
    if dx > 0:
        lbl = 0
        if dx > 1:
            lbl = poss[dx-2]+1
        lbr = poss[dx-1]
        rbl = n-1
        if len(poss) != dx:
            rbl = poss[dx] -1
        result += (lbr-lbl+1) * (rbl-x+1) * i
    # 右に1番目の数がある
    if dx < len(poss):
        rbr = n-1
        if dx < len(poss) -1:
            rbr = poss[dx+1]-1
        rbl = poss[dx]
        lbr = 0
        if dx > 0:
            lbr = poss[dx-1] +1
        result += (rbr-rbl+1) * (x-lbr+1) * i
    used.add(x)

print(result)

Submission status: Wrong Answer

Solution code:
#!/usr/bin/python3
# -*- coding: utf-8 -*-



N = int(input())
Pn = list(map(int, input().split()))

In = [0] * (N+1)
for i in range(N):
  In[Pn[i]] = i+1
print(Pn)
print(In)

cnt = 0
l = [0] + [i for i in range(N+1)]
r = [i+1 for i in range((N+1))] + [N+1]

for v in range(1, N+1):
  i = In[v]
  
  l1 = l[i]
  l2 = l[l1]
  r1 = r[i]
  r2 = r[r1]
  cnt += ((l1-l2) * (r1-i) + (i-l1) * (r2-r1)) * v
  
  l[r1] = l1
  r[l1] = r1
    
print(cnt)

Submission status: Wrong Answer

Solution code:
from collections import deque

def f(Q):
    if len(Q)==2:
        return min(Q)
    else:
        s = 0
        r = Q.popleft()
        Max = r
        second_Max = 0
        for q in Q:
            if q>Max:
                second_Max = Max
                Max = q
            elif second_Max<q<=Max:
                second_Max = q
            s += second_Max
        print(s)
        return(f(Q) + s)

Submission status: Wrong Answer

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
from random import shuffle
sys.setrecursionlimit(200000)
# local only
# if not __debug__:
#     fin = open('text.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 RBNode:
    def __init__(self, val, is_red, parent=None, left=None, right=None):
        self.val = val
        self.parent = parent
        self.left = left
        self.right = right
        self.color = is_red


class RBTree:
    def __init__(self):
        self.root = None

    def left_rotate(self, node):
        # set the node as the left child node of the current node's right node
        right_node = node.right
        if right_node is None:
            return
        else:
            # right node's left node become the right node of current node
            node.right = right_node.left
            if right_node.left is not None:
                right_node.left.parent = node
            right_node.parent = node.parent
            # check the parent case
            if node.parent is None:
                self.root = right_node
            elif node is node.parent.left:
                node.parent.left = right_node
            else:
                node.parent.right = right_node
            right_node.left = node
            node.parent = right_node

    def right_rotate(self, node):
        # set the node as the right child node of the current node's left node
        left_node = node.left
        if left_node is None:
            return
        else:
            # left node's right  node become the left node of current node
            node.left = left_node.right
            if left_node.right is not None:
                left_node.right.parent = node
            left_node.parent = node.parent
            # check the parent case
            if node.parent is None:
                self.root = left_node
            elif node is node.parent.left:
                node.parent.left = left_node
            else:
                node.parent.right = left_node
            left_node.right = node
            node.parent = left_node

    def insert(self, node):
        # the inserted node's color is default is red
        root = self.root
        insert_node_parent = None
        # find the position of inserted node
        while root is not None:
            insert_node_parent = root
            if insert_node_parent.val < node.val:
                root = root.right
            else:
                root = root.left
        # set the n ode's parent node
        node.parent = insert_node_parent
        if insert_node_parent is None:
            # case 1  inserted tree is null
            self.root = node
        elif insert_node_parent.val > node.val:
            # case 2 not null and find left or right
            insert_node_parent.left = node
        else:
            insert_node_parent.right = node
        node.left = None
        node.right = None
        node.color = 1
        # fix the tree to
        self.fix_insert(node)

    def fix_insert(self, node):
        # case 1 the parent is null, then set the inserted node as root and color = 0
        if node.parent is None:
            node.color = 0
            self.root = node
            return
            # case 2 the parent color is black, do nothing
        # case 3 the parent color is red
        while node.parent and node.parent.color == 1:
            if node.parent is node.parent.parent.left:
                uncle_node = node.parent.parent.right
                if uncle_node and uncle_node.color == 1:
                    # case 3.1 the uncle node is red
                    # then set parent and uncle color is black and grandparent is red
                    # then node => node.parent
                    node.parent.color = 0
                    node.parent.parent.right.color = 0
                    node.parent.parent.color = 1
                    node = node.parent.parent
                    continue
                elif node is node.parent.right:
                    # case 3.2 the uncle node is black or null, and the node is right of parent
                    # then set his parent node is current node
                    # left rotate the node and continue the next
                    node = node.parent
                    self.left_rotate(node)
                # case 3.3 the uncle node is black and parent node is left
                # then parent node set black and grandparent set red
                node.parent.color = 0
                node.parent.parent.color = 1
                self.right_rotate(node.parent.parent)
            else:
                uncle_node = node.parent.parent.left
                if uncle_node and uncle_node.color == 1:
                    # case 3.1 the uncle node is red
                    # then set parent and uncle color is black and grandparent is red
                    # then node => node.parent
                    node.parent.color = 0
                    node.parent.parent.left.color = 0
                    node.parent.parent.color = 1
                    node = node.parent.parent
                    continue
                elif node is node.parent.left:
                    # case 3.2 the uncle node is black or null, and the node is right of parent
                    # then set his parent node is current node
                    # left rotate the node and continue the next
                    node = node.parent
                    self.right_rotate(node)
                # case 3.3 the uncle node is black and parent node is left
                # then parent node set black and grandparent set red
                node.parent.color = 0
                node.parent.parent.color = 1
                self.left_rotate(node.parent.parent)
        self.root.color = 0

    def transplant(self, node_u, node_v):
        """
        replace u with v
        :param node_u: replaced node
        :param node_v:
        :return: None
        """
        if node_u.parent is None:
            self.root = node_v
        elif node_u is node_u.parent.left:
            node_u.parent.left = node_v
        elif node_u is node_u.parent.right:
            node_u.parent.right = node_v
        # check is node_v is None
        if node_v:
            node_v.parent = node_u.parent

    def find(self, key):
        node = self.root
        while node is not None:
            if node.val < key:
                node = node.right
            elif node.val > key:
                node = node.left
            else:
                return node
        return None

    def maximum(self, node):
        """
        find the max node when node regard as a root node
        :param node:
        :return: max node
        """
        temp_node = node
        while temp_node.right is not None:
            temp_node = temp_node.right
        return temp_node

    def minimum(self, node):
        """
        find the minimum node when node regard as a root node
        :param node:
        :return: minimum node
        """
        temp_node = node
        while temp_node.left:
            temp_node = temp_node.left
        return temp_node

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

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

    def delete(self, node):
        # find the node position
        node_color = node.color
        if node.left is None:
            temp_node = node.right
            self.transplant(node, node.right)
        elif node.right is None:
            temp_node = node.left
            self.transplant(node, node.left)
        else:
            # both child exits ,and find minimum child of right child
            node_min = self.minimum(node.right)
            node_color = node_min.color
            temp_node = node_min.right
            ##
            if node_min.parent != node:
                self.transplant(node_min, node_min.right)
                node_min.right = node.right
                node_min.right.parent = node_min
            self.transplant(node, node_min)
            node_min.left = node.left
            node_min.left.parent = node_min
            node_min.color = node.color
        # when node is black, then need to fix it with 4 cases
        if node_color == 0:
            self.delete_fixup(temp_node)

    def delete_fixup(self, node):
        # 4 cases
        while node != self.root and node.color == 0:
            # node is not root and color is black
            if node == node.parent.left:
                # node is left node
                node_brother = node.parent.right

                # case 1: node's red, can not get black node
                # set brother is black and parent is red
                if node_brother.color == 1:
                    node_brother.color = 0
                    node.parent.color = 1
                    self.left_rotate(node.parent)
                    node_brother = node.parent.right

                # case 2: brother node is black, and its children node is both black
                if (node_brother.left is None or node_brother.left.color == 0) and (
                        node_brother.right is None or node_brother.right.color == 0):
                    node_brother.color = 1
                    node = node.parent
                else:

                    # case 3: brother node is black , and its left child node is red and right is black
                    if node_brother.right is None or node_brother.right.color == 0:
                        node_brother.color = 1
                        node_brother.left.color = 0
                        self.right_rotate(node_brother)
                        node_brother = node.parent.right

                    # case 4: brother node is black, and right is red, and left is any color
                    node_brother.color = node.parent.color
                    node.parent.color = 0
                    node_brother.right.color = 0
                    self.left_rotate(node.parent)
                node = self.root
                break
            else:
                node_brother = node.parent.left
                if node_brother.color == 1:
                    node_brother.color = 0
                    node.parent.color = 1
                    self.left_rotate(node.parent)
                    node_brother = node.parent.right
                if (node_brother.left is None or node_brother.left.color == 0) and (
                        node_brother.right is None or node_brother.right.color == 0):
                    node_brother.color = 1
                    node = node.parent
                else:
                    if node_brother.left is None or node_brother.left.color == 0:
                        node_brother.color = 1
                        node_brother.right.color = 0
                        self.left_rotate(node_brother)
                        node_brother = node.parent.left
                    node_brother.color = node.parent.color
                    node.parent.color = 0
                    node_brother.left.color = 0
                    self.right_rotate(node.parent)
                node = self.root
                break
        node.color = 0

    def inorder(self):
        res = []
        if not self.root:
            return res
        stack = []
        root = self.root
        stack.append(root)
        while stack:
            root = stack.pop()
            res.append({'val': root.val, 'color': root.color})
            if root.left:
                stack.append(root.left)
            if root.right:
                stack.append(root.right)
        # while root or stack:
        #     while root:
        #         stack.append(root)
        #         root = root.left
        #     root = stack.pop()
        #     res.append({'val': root.val, 'color': root.color})
        #     root = root.right
        return res



def main():
    N = ii()
    P = lmi()
    L = [0 for i in range(N)]
    for i in range(N):
        L[P[i] - 1] = i
    L.reverse()
    print(L)
    ans = 0
    rb = RBTree()
    for num, i in enumerate(L):
        rb.insert(RBNode(i, 1))
        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)) * (N - num)
    print(ans)
    # 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
    # N = 100000
    # a = [i for i in range(N)]
    # shuffle(a)
    # with open('text.txt', 'w') as f:
    #     f.write(str(N))
    #     f.write('\n')
    #     for i in range(N):
    #         f.write(str(a[i]))
    #         f.write(' ')
    #     f.write('\n')
    return



if __name__ == '__main__':
    main()

Submission status: Wrong Answer

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

score = 0
new_list = sorted(P)
for idx, i in enumerate(new_list):
  if idx+1 < N: 
    score += (idx+1)*i
print(score)

Submission status: Wrong Answer

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

score = 0
new_list = sorted(P)
for idx, i in enumerate(new_list):
  if idx == 0:
    continue
  else:
    score += (N-idx)*i
print(score)