Problem:


Score : 400 points

Problem Statement

One day, Snuke was given a permutation of length N, a_1, a_2, ..., a_N, from his friend.

Find the following:

Constraints

1 ≦ N ≦ 200,000

(a_1, a_2, ..., a_N) is a permutation of (1, 2, ..., N).

Input

The input is given from Standard Input in the following format:

N
a_1 a_2 ... a_N

Output

Print the answer.

Note that the answer may not fit into a 32-bit integer.

Sample Input 1

3
2 1 3

Sample Output 1

9

Sample Input 2

4
1 3 2 4

Sample Output 2

19

Sample Input 3

8
5 4 8 1 2 6 7 3

Sample Output 3

85



Sample input:
3
2 1 3


Sample output:
9

Submission status: Accepted

Solution code:
from bisect import*
class BTreeNode:
    def __init__(self):self.key,self.child=[],[]
root=BTreeNode()
def main():
    def search_higher(key):
        ptr=root
        ret=None
        while ptr.child:
            i=bisect(ptr.key,key)
            if i!=len(ptr.key):ret=ptr.key[i]
            ptr=ptr.child[i]
        i=bisect(ptr.key,key)
        if i!=len(ptr.key):ret=ptr.key[i]
        return ret
    def search_lower(key):
        ptr=root
        ret=None
        while ptr.child:
            i=bisect_left(ptr.key,key)
            if i:ret=ptr.key[i-1]
            ptr=ptr.child[i]
        i=bisect_left(ptr.key,key)
        if i:ret=ptr.key[i-1]
        return ret
    def insert_rec(ptr,key):
        b_size=512
        if not ptr.child:
            insort(ptr.key,key)
            if len(ptr.key)==b_size*2-1:
                ret=BTreeNode()
                ret.key=ptr.key[:b_size]
                ptr.key=ptr.key[b_size:]
                return ret
        else:
            i=bisect(ptr.key,key)
            tmp=insert_rec(ptr.child[i],key)
            if tmp:
                ptr.key.insert(i,tmp.key.pop())
                ptr.child.insert(i,tmp)
                if len(ptr.child)==b_size*2:
                    ret=BTreeNode()
                    ret.child=ptr.child[:b_size]
                    ptr.child=ptr.child[b_size:]
                    ret.key=ptr.key[:b_size]
                    ptr.key=ptr.key[b_size:]
                    return ret
    def insert(key):
        global root
        tmp=insert_rec(root,key)
        if tmp:
            p=BTreeNode()
            p.key=[tmp.key.pop()]
            p.child=[tmp,root]
            root=p
    n,*a=map(int,open(0).read().split())
    l=[0]*n
    for i,v in enumerate(a,1):l[v-1]=i
    insert(0)
    insert(n+1)
    c=0
    for i,v in enumerate(l,1):
        c+=(search_higher(v)-v)*(v-search_lower(v))*i
        insert(v)
    print(c)
main()

Submission status: Accepted

Solution code:
from bisect import*
class BTreeNode:
    def __init__(self):self.key,self.child=[],[]
class BTree:
    def __init__(self):self.root=BTreeNode()
    def search_higher(self,key):
        ptr=self.root
        ret=None
        while ptr.child:
            i=bisect(ptr.key,key)
            if i!=len(ptr.key):ret=ptr.key[i]
            ptr=ptr.child[i]
        i=bisect(ptr.key,key)
        if i!=len(ptr.key):ret=ptr.key[i]
        return ret
    def search_lower(self,key):
        ptr=self.root
        ret=None
        while ptr.child:
            i=bisect_left(ptr.key,key)
            if i:ret=ptr.key[i-1]
            ptr=ptr.child[i]
        i=bisect_left(ptr.key,key)
        if i:ret=ptr.key[i-1]
        return ret
    def insert(self,key):
        def insert_rec(ptr):
            b_size=512
            if not ptr.child:
                insort(ptr.key,key)
                if len(ptr.key)==b_size*2-1:
                    ret=BTreeNode()
                    ret.key=ptr.key[:b_size]
                    ptr.key=ptr.key[b_size:]
                    return ret
            else:
                i=bisect(ptr.key,key)
                tmp=insert_rec(ptr.child[i])
                if tmp:
                    ptr.key.insert(i,tmp.key.pop())
                    ptr.child.insert(i,tmp)
                    if len(ptr.child)==b_size*2:
                        ret=BTreeNode()
                        ret.child=ptr.child[:b_size]
                        ptr.child=ptr.child[b_size:]
                        ret.key=ptr.key[:b_size]
                        ptr.key=ptr.key[b_size:]
                        return ret
        tmp=insert_rec(self.root)
        if tmp:
            root=BTreeNode()
            root.key=[tmp.key.pop()]
            root.child=[tmp,self.root]
            self.root=root
def main():
    n,*a=map(int,open(0).read().split())
    l=[0]*n
    for i,v in enumerate(a,1):l[v-1]=i
    t=BTree()
    t.insert(0)
    t.insert(n+1)
    c=0
    for i,v in enumerate(l,1):
        c+=(t.search_higher(v)-v)*(v-t.search_lower(v))*i
        t.insert(v)
    print(c)
main()

Submission status: Accepted

Solution code:
from bisect import*
class BTreeNode:
    def __init__(self):self.key,self.child=[],[]
class BTree:
    def __init__(self):self.root=BTreeNode()
    def search_higher(self,key):
        ptr=self.root
        ret=None
        while ptr.child:
            i=bisect(ptr.key,key)
            if i!=len(ptr.key):ret=ptr.key[i]
            ptr=ptr.child[i]
        i=bisect(ptr.key,key)
        if i!=len(ptr.key):ret=ptr.key[i]
        return ret
    def search_lower(self,key):
        ptr=self.root
        ret=None
        while ptr.child:
            i=bisect_left(ptr.key,key)
            if i:ret=ptr.key[i-1]
            ptr=ptr.child[i]
        i=bisect_left(ptr.key,key)
        if i:ret=ptr.key[i-1]
        return ret
    def insert(self,key):
        def insert_rec(ptr,key):
            b_size=512
            if not ptr.child:
                insort(ptr.key,key)
                if len(ptr.key)==b_size*2-1:
                    ret=BTreeNode()
                    ret.key=ptr.key[:b_size]
                    ptr.key=ptr.key[b_size:]
                    return ret
            else:
                i=bisect(ptr.key,key)
                tmp=insert_rec(ptr.child[i],key)
                if tmp:
                    ptr.key.insert(i,tmp.key.pop())
                    ptr.child.insert(i,tmp)
                    if len(ptr.child)==b_size*2:
                        ret=BTreeNode()
                        ret.child=ptr.child[:b_size]
                        ptr.child=ptr.child[b_size:]
                        ret.key=ptr.key[:b_size]
                        ptr.key=ptr.key[b_size:]
                        return ret
        tmp=insert_rec(self.root,key)
        if tmp:
            root=BTreeNode()
            root.key=[tmp.key.pop()]
            root.child=[tmp,self.root]
            self.root=root
def main():
    n,*a=map(int,open(0).read().split())
    l=[0]*n
    for i,v in enumerate(a,1):l[v-1]=i
    t=BTree()
    t.insert(0)
    t.insert(n+1)
    c=0
    for i,v in enumerate(l,1):
        c+=(t.search_higher(v)-v)*(v-t.search_lower(v))*i
        t.insert(v)
    print(c)
main()

Submission status: Accepted

Solution code:
from bisect import*
class BTreeNode:
    def __init__(self):self.key,self.child=[],[]
class BTree:
    def __init__(self):self.root=BTreeNode()
    def search_higher(self,key):
        ptr=self.root
        ret=None
        while ptr.child:
            i=bisect(ptr.key,key)
            if i!=len(ptr.key):ret=ptr.key[i]
            ptr=ptr.child[i]
        i=bisect(ptr.key,key)
        if i!=len(ptr.key):ret=ptr.key[i]
        return ret
    def search_lower(self,key):
        ptr=self.root
        ret=None
        while ptr.child:
            i=bisect_left(ptr.key,key)
            if i:ret=ptr.key[i-1]
            ptr=ptr.child[i]
        i=bisect_left(ptr.key,key)
        if i:ret=ptr.key[i-1]
        return ret
    def insert(self,key):
        def insert_rec(ptr,key):
            b_size=512
            if not ptr.child:
                insort(ptr.key,key)
                if len(ptr.key)==b_size*2-1:
                    ret=BTreeNode()
                    ret.key=ptr.key[:b_size]
                    ptr.key=ptr.key[b_size:]
                    return ret
            else:
                i=bisect(ptr.key,key)
                tmp=insert_rec(ptr.child[i],key)
                if tmp:
                    ptr.key.insert(i,tmp.key.pop())
                    ptr.child.insert(i,tmp)
                    if len(ptr.child)==b_size*2:
                        ret=BTreeNode()
                        ret.child=ptr.child[:b_size]
                        ptr.child=ptr.child[b_size:]
                        ret.key=ptr.key[:b_size]
                        ptr.key=ptr.key[b_size:]
                        return ret
                return None
        tmp=insert_rec(self.root,key)
        if tmp:
            root=BTreeNode()
            root.key=[tmp.key.pop()]
            root.child=[tmp,self.root]
            self.root=root
def main():
    n,*a=map(int,open(0).read().split())
    l=[0]*n
    for i,v in enumerate(a,1):l[v-1]=i
    t=BTree()
    t.insert(0)
    t.insert(n+1)
    c=0
    for i,v in enumerate(l,1):
        c+=(t.search_higher(v)-v)*(v-t.search_lower(v))*i
        t.insert(v)
    print(c)
main()

Submission status: Accepted

Solution code:
import bisect


class BTreeNode:
    def __init__(self):
        self.key = []
        self.child = []


class BTree:
    def __init__(self):
        self.root = BTreeNode()

    def search_higher(self, key):
        ptr = self.root
        ret = None
        while ptr.child:
            i = bisect.bisect_right(ptr.key, key)
            if i != len(ptr.key):
                ret = ptr.key[i]
            ptr = ptr.child[i]
        i = bisect.bisect_right(ptr.key, key)
        if i != len(ptr.key):
            ret = ptr.key[i]
        return ret

    def search_lower(self, key):
        ptr = self.root
        ret = None
        while ptr.child:
            i = bisect.bisect_left(ptr.key, key)
            if i != 0:
                ret = ptr.key[i - 1]
            ptr = ptr.child[i]
        i = bisect.bisect_left(ptr.key, key)
        if i != 0:
            ret = ptr.key[i - 1]
        return ret

    def insert(self, key):
        def insert_rec(ptr):
            b_size = 512
            if not ptr.child:
                bisect.insort(ptr.key, key)
                if len(ptr.key) == b_size * 2 - 1:
                        ret = BTreeNode()
                        ret.key = ptr.key[:b_size]
                        ptr.key = ptr.key[b_size:]
                        return ret
            else:
                i = bisect.bisect(ptr.key, key)
                temp = insert_rec(ptr.child[i])
                if temp is not None:
                    ptr.key.insert(i, temp.key.pop(-1))
                    ptr.child.insert(i, temp)
                    if len(ptr.child) == b_size * 2:
                        ret = BTreeNode()
                        ret.child = ptr.child[:b_size]
                        ptr.child = ptr.child[b_size:]
                        ret.key = ptr.key[:b_size]
                        ptr.key = ptr.key[b_size:]
                        return ret
            return None
        temp = insert_rec(self.root)
        if temp is not None:
            root = BTreeNode()
            root.key = [temp.key.pop(-1)]
            root.child = [temp, self.root]
            self.root = root

    def dump(self):
        def dump_rec(ptr, dep):
            for _ in range(0, dep):
                print("  ", end="")
            print(ptr.key)
            for c in ptr.child:
                dump_rec(c, dep + 1)
        dump_rec(self.root, 0)
        print("")


def main():
    n,*a=map(int,open(0).read().split())
    l=[0]*n
    for i,v in enumerate(a,1):l[v-1]=i
    t=BTree()
    t.insert(0)
    t.insert(n+1)
    c=0
    for i,v in enumerate(l,1):
        c+=(t.search_higher(v)-v)*(v-t.search_lower(v))*i
        t.insert(v)
    print(c)
main()

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
ans=0
n=int(input())
A=list(map(int,input().split()))
B=[0]*(n+1)
for i in range(n):
    B[A[i]]=i+1
LL=[int(i) for i in range(n+2)]
RR=[int(i) for i in range(n+2)]
for i in range(n,0,-1):
    l=LL[B[i]]
    r=RR[B[i]]
    ans+=(B[i]-l+1)*(r-B[i]+1)*i
    LL[r+1]=l
    RR[l-1]=r
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
class UnionFind:
    __slots__ = ['id','sz']

    def __init__(self, n):
        self.id = [-1] * n

    def root(self, x):
        if self.id[x] < 0:
            return x
        else:
            self.id[x] = self.root(self.id[x])
            return self.id[x]

    def find(self, x, y):
        return uf.root(x) == uf.root(y)

    def union(self, x, y):
        s1, s2 = self.root(x), self.root(y)
        if s1 != s2:
            if self.id[s1] <= self.id[s2]:
                self.id[s1] += self.id[s2]
                self.id[s2] = s1
            else:
                self.id[s2] += self.id[s1]
                self.id[s1] = s2
            return True
        return False

n = int(input())
a = list(map(int,input().split()))
uf = UnionFind(n)
ans=0
data=[0]*n
b=[0]*(n+1)
for i in range(n):
    b[a[i]]=i
for i in range(n,0,-1):
    r,l=0,0
    data[b[i]]=i
    if b[i]+1 <= n-1:
        if data[b[i]+1]>0:
            uf.union(b[i],b[i]+1)
    r=-uf.id[uf.root(b[i])]

    if b[i]-1>=0 and data[b[i]-1]>0:
        uf.union(b[i],b[i]-1)
    l=1-uf.id[uf.root(b[i])]-r
    ans+=(r*l)*i
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
a = list(map(int,input().split()))
l = [i for i in range(N)]
r = [i for i in range(N)]

b = [0] * N
for i in range(N):
    b[a[i]-1] = i

ans = 0
for i in range(N-1,-1,-1):
    m = b[i]
    x,y = l[m],r[m]
    ans += (i+1)*(m-x+1)*(y-m+1)
    l[min(y+1,N-1)] = x
    r[max(x-1,0)] = y
print(ans)

Submission status: Accepted

Solution code:
N = int(input())
A = [int(x) for x in input().split()]
B = [0] * (N + 1)
for i in range(N):
  B[A[i]] = i + 1
L = list(range(N + 2))
R = list(range(N + 2))
cnt = 0
for i in range(N, 0, -1):
  l = L[B[i]]
  r = R[B[i]]
  cnt += i * (B[i] - l + 1) * (r - B[i] + 1)
  L[r + 1] = l
  R[l - 1] = r
print(cnt)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

import sys

def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

class BIT:

    def __init__(self, n):
        # 0-indexed
        nv = 1
        while nv < n:
            nv *= 2
        self.size = nv
        self.tree = [0] * nv

    def sum(self, i):
        """ [0, i]を合計する """
        s = 0
        i += 1
        while i > 0:
            s += self.tree[i-1]
            i -= i & -i
        return s

    def add(self, i, x):
        """ 値の追加：添字i, 値x """
        i += 1
        while i <= self.size:
            self.tree[i-1] += x
            i += i & -i

    def get(self, l, r=None):
        """ 区間和の取得 [l, r) """
        # 引数が1つなら一点の値を取得
        if r is None: r = l + 1
        res = 0
        if r: res += self.sum(r-1)
        if l: res -= self.sum(l-1)
        return res

def bisearch_min(mn, mx, func):
    """ 条件を満たす最小値を見つける二分探索 """
    ok = mx
    ng = mn
    while ng+1 < ok:
        mid = (ok+ng) // 2
        if func(mid):
            # 下を探しに行く
            ok = mid
        else:
            # 上を探しに行く
            ng = mid
    return ok

def bisearch_max(mn, mx, func):
    """ 条件を満たす最大値を見つける二分探索 """
    ok = mn
    ng = mx
    while ok+1 < ng:
        mid = (ok+ng) // 2
        if func(mid):
            # 上を探しに行く
            ok = mid
        else:
            # 下を探しに行く
            ng = mid
    return ok

# m~idxの間に出現済がない(この範囲の中で自分が最小値)かどうか
def calc1(m):
    cnt = lend - bit.sum(m-1)
    return cnt == 0

# idx~mの間に出現済がない(この範囲の中で自分が最小値)かどうか
def calc2(m):
    cnt = bit.sum(m) - rstart
    return cnt == 0

N = INT()
A = LIST()
# aの昇順に処理できるようにindexで並べておく
idxs = [0] * (N+1)
for i, a in enumerate(A):
    idxs[a] = i + 1

bit = BIT(N+2)
# 先頭と末尾に番兵を仕込む
bit.add(0, 1)
bit.add(N+1, 1)
ans = [0] * (N+1)
for a in range(1, N+1):
    # a(1~N)が格納されているindex
    idx = idxs[a]
    # 左の終点と右の始点は各回固定なので先に取っておく
    lend = bit.sum(idx)
    rstart = bit.sum(idx-1)
    # 自分より小さいindexで最初に自分より小さい値がある場所
    l = bisearch_min(0, idx+1, calc1)
    # 自分より大きいindexで最初に自分より小さい値がある場所
    r = bisearch_max(idx, N+1, calc2)
    # aを使う回数 * a = 左端として使える範囲 * 右端として使える範囲 * a
    ans[a] = (idx-l+1) * (r-idx+1) * a
    # aを出現済とする
    bit.add(idx, 1)
# 全てのaについての合計
print(sum(ans))

Submission status: Accepted

Solution code:
n=int(input())
a=[int(j) for j in input().split()]
ans=0
l=list(range(n+2))
r=list(range(n+2))

index=[0]*(n+1)
for i in range(n):
    index[a[i]]=i

for i in range(1,n+1)[::-1]:
    ind=index[i]
    x,y=l[ind],r[ind]
    ans+=i*(ind-x+1)*(y-ind+1)
    l[y+1],r[x-1]=x,y
print(ans)

Submission status: Accepted

Solution code:
N=int(input())
a=[0]+[int(i) for i in input().split()]
par=[0 for i in range(N+1)]
size=[0 for i in range(N+1)]
def find(x):
    if (par[x]==x):
        return x
    par[x]=find(par[x])
    return par[x]
def unite(x,y):
    x=find(x)
    y=find(y)
    res=size[x]*size[y]
    size[x]+=size[y]
    par[y]=x
    return res
for i in range(N+1):
    par[i]=i
    size[i]=1
b=[0 for i in range(N+1)]
for i in range(N+1):
    b[a[i]]=i
ans=0
for j in range(1,N+1)[::-1]:
    i=b[j]
    ans+=a[i]
    if i-1>=1 and a[i-1]>a[i]:
        ans+=unite(i-1,i)*a[i]
    if i+1<=N and a[i+1]>a[i]:
        ans += unite(i+1,i)*a[i]
print(ans)

Submission status: Accepted

Solution code:
root=lambda x:x if par[x]==x else root(par[x])
same=lambda x,y:root(x)==root(y)
def unite(*z):
  x,y=map(root,z)
  if x!=y:
    if rank[x]<rank[y]:
      par[x]=y
      size[y]+=size[x]
    else:
      par[y]=x
      size[x]+=size[y]
      if rank[x]==rank[y]:rank[x]+=1
n,*a=map(int,open(0).read().split())
*par,=range(n)
rank=[1]*n
size=[1]*n
b=[0]*n
for i,t in enumerate(a):b[t-1]=i
c=0
for k in b[::-1]:
  l=r=1
  if k>0 and a[k-1]>a[k]:
    l+=size[root(k-1)]
    unite(k-1,k)
  if k+1<n and a[k+1]>a[k]:
    r+=size[root(k+1)]
    unite(k+1,k)
  c+=l*r*a[k]
print(c)

Submission status: Accepted

Solution code:
class SparseTable():
    def __init__(self, array, n):
        '''テーブルを構築する'''
        self.row_size = n.bit_length()

        # log_tableを構築する
        # log_table = [0, 0, 1, 1, 2, 2, 2, 2, ...]
        self.log_table = [0] * (n + 1)
        for i in range(2, n + 1):
            self.log_table[i] = self.log_table[i//2] + 1

        # sparse_tableを構築する
        self.sparse_table = [[0] * n for _ in range(self.row_size)]
        for i in range(n):
            self.sparse_table[0][i] = array[i]
        for row in range(1, self.row_size):
            for i in range(n - (1 << row) + 1):
               self.sparse_table[row][i] = self._merge(self.sparse_table[row - 1][i], \
                                                       self.sparse_table[row - 1][i + (1 << row - 1)])

    def _merge(self, num1, num2):
        '''クエリの内容'''
        return min(num1, num2)

    def query(self, l, r):
        '''区間[l, r)に対するクエリに答える'''
        if r == l:
            return None
        row = self.log_table[r - l]
        return self._merge(self.sparse_table[row][l], self.sparse_table[row][r - (1 << row)])
  
n = int(input())
a = list(map(int, input().split()))
st = SparseTable(a, n)
ans = 0
for i in range(n):
    ok = i + 1
    ng = n + 1
    while abs(ok - ng) > 1:
        mid = (ok + ng) // 2
        if st.query(ok, mid) < a[i]:
            ng = mid
        else:
            ok = mid
    tmp1 = ok - i - 1
    
    ok = i
    ng = -1
    mid = (ok + ng) // 2
    while abs(ok - ng) > 1:
        mid = (ok + ng) // 2
        if st.query(mid, i + 1) < a[i]:
            ng = mid
        else:
            ok = mid
    tmp2 = i - ok
    ans += ((tmp1+1) * (tmp2+1))* a[i]
print(ans)

Submission status: Accepted

Solution code:
import sys
import heapq
from operator import itemgetter
from collections import deque, defaultdict
from bisect import bisect_left, bisect_right
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

def sol():
    N = int(input())
    A = [int(x) for x in input().split()]

    indexList = {x : i for i, x in enumerate(A)}

    V = set()
    rootList = {}
    size = {}

    def getRoot(index):
        parent = rootList[index]
        if parent == index:
            return index
        root = getRoot(parent)
        rootList[index] = root
        return root

    def union(x, y):
        rootX, rootY = getRoot(x), getRoot(y)
        sX, sY = size[rootX], size[rootY]
        if sX > sY:
            sX, sY = sY, sX
            rootX, rootY = rootY, rootX
        rootList[rootX] = rootY
        size[rootY] += sX

    ans = 0
    for x in range(N, 0, -1):
        index = indexList[x]
        V.add(index)
        size[index] = 1
        rootList[index] = index
        left, right = 0, 0

        if index - 1 in V:
            left = size[getRoot(index - 1)]
            union(index, index - 1)
        if index + 1 in V:
            right = size[getRoot(index + 1)]
            union(index, index + 1)

        count = (left + 1) * (right + 1)
        ans += x * count

    print(ans)


sol()

Submission status: Accepted

Solution code:
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)

# 大きい数字から追加していく。そのときの連結成分の大きさだけ足される。
# union findっぽく。各成分の左端を根として持つ

N = int(input())
A = [int(x) for x in input().split()]

x_to_i = {x:i for i,x in enumerate(A)}

V = set()
root = dict()
size = dict()

def find_root(x):
    y = root[x]
    if x == y:
        return y
    ry = find_root(y)
    root[x] = ry
    return ry

def merge(x,y):
    rx = find_root(x)
    ry = find_root(y)
    sx = size[rx]
    sy = size[ry]
    if sx > sy:
        rx,ry = ry,rx
        sx,sy = sy,sx
    root[rx] = ry
    size[ry] += sx

answer = 0
for x in range(N,0,-1):
    i = x_to_i[x]
    V.add(i)
    size[i] = 1
    root[i] = i
    left = 0
    right = 0
    if i-1 in V:
        left = size[find_root(i-1)]
        merge(i-1,i)
    if i+1 in V:
        right = size[find_root(i+1)]
        merge(i+1,i)
    cnt = (left+1) * (right+1)
    answer += x * cnt

print(answer)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10000000)
def input():
    return sys.stdin.readline()[:-1]
from bisect import *
from collections import *
from heapq import *
from math import *
from itertools import *

class UnionFind:

    def __init__(self, n):
        self.n = n
        self.par = [i for i in range(n)]
        self.height = [0 for i in range(n)]
        self.size = [1 for i in range(n)]

    def find(self, x):
        if self.par[x] == x:
            return x
        self.par[x] = self.find(self.par[x])
        return self.par[x]

    def getSize(self, x):
        return self.size[self.find(x)]

    def unite(self, x, y):
        x, y = self.find(x), self.find(y)
        if x == y:
            return
        if self.height[x] < self.height[y]:
            self.par[x] = y
            self.size[y] += self.size[x]
        else:
            self.par[y] = self.par[x]
            self.size[x] += self.size[y]
            if self.height[x] == self.height[x]:
                self.height[x] += 1

    def same(self, x, y):
        return self.find(x) == self.find(y)

N = int(input())
A = list(map(int, input().split()))
B = [-1] * (N+1)
for i, a in enumerate(A):
    B[a] = i
uf = UnionFind(N)
ans = 0
for x in range(N, 0, -1):
    i, l, r = B[x], 0, 0
    if 0 < i and A[i] < A[i-1]:
        l = uf.getSize(i-1)
        uf.unite(i-1, i)
    if i < N-1 and A[i] < A[i+1]:
        r = uf.getSize(i+1)
        uf.unite(i, i+1)
    ans += (l+1)*(r+1)*x
print(ans)

Submission status: Accepted

Solution code:
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7

N = int(sys.stdin.readline())
A = list(map(int, sys.stdin.readline().split()))

pos = [0] * (N + 1)
pos[0] = -1
for i, a in enumerate(A):
    pos[a] = i

ans = 0
lefts = [0] * N
rights = [0] * N
for i in reversed(range(1, N + 1)):
    p = pos[i]
    if p + 1 < N and A[p + 1] > i:
        # 右とつながった
        right = rights[p + 1]
    else:
        right = p
    if p - 1 >= 0 and A[p - 1] > i:
        # 左とつながった
        left = lefts[p - 1]
    else:
        left = p
    lefts[right] = left
    rights[left] = right
    ans += (p - left + 1) * (right - p + 1) * i
print(ans)

Submission status: Accepted

Solution code:
import itertools
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7

N = int(sys.stdin.readline())
A = list(map(int, sys.stdin.readline().split()))

pos = [0] * (N + 1)
pos[0] = -1
for i, a in enumerate(A):
    pos[a] = i

ans = 0
lefts = [0] * N
rights = [0] * N
for i in reversed(range(1, N + 1)):
    p = pos[i]
    if p + 1 < N and A[p + 1] > i:
        # 右とつながった
        right = rights[p + 1]
    else:
        right = p
    if p - 1 >= 0 and A[p - 1] > i:
        # 左とつながった
        left = lefts[p - 1]
    else:
        left = p
    lefts[right] = left
    rights[left] = right
    ans += (p - left + 1) * (right - p + 1) * i
print(ans)

Submission status: Accepted

Solution code:
import itertools
import os
import sys

if os.getenv("LOCAL"):
    sys.stdin = open("_in.txt", "r")

sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7

N = int(sys.stdin.readline())
A = list(map(int, sys.stdin.readline().split()))


def gutyocu():
    ans = 0
    for i, j in itertools.combinations_with_replacement(range(N), r=2):
        ans += min(A[i: j + 1])
    return ans


pos = list(range(N + 1))
pos[0] = -1
for i, a in enumerate(A):
    pos[a] = i

ans = 0
lefts = list(range(N + 1))
rights = list(range(N + 1))
for i in reversed(range(1, N + 1)):
    p = pos[i]
    if p + 1 < N and A[p + 1] > i:
        # 右とつながった
        right = rights[p + 1]
    else:
        right = p
    if p - 1 >= 0 and A[p - 1] > i:
        # 左とつながった
        left = lefts[p - 1]
    else:
        left = p
    lefts[right] = left
    rights[left] = right
    ans += (abs(left - p) + 1) * (abs(right - p) + 1) * i
print(ans)

Submission status: Accepted

Solution code:
N=int(input())
A=list(map(int,input().split()))
p=[None]*N
for i,a in enumerate(A):
    p[a-1]=i
ans=0
l,r=[i for i in range(N)],[i for i in range(N)]
for i in range(N-1,-1,-1):
    left,right=l[p[i]],r[p[i]]
    ans+=(i+1)*(p[i]-left+1)*(right-p[i]+1)
    if left>0:
        r[left-1]=right
    if right<N-1:
        l[right+1]=left
print(ans)

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int, a: "List[int]"):
    idx = {aa: i for i, aa in enumerate(a)}
    left = [i for i in range(N+2)]
    right = [i for i in range(N+2)]
    res = 0
    for n in range(N, 0, -1):
        i = idx[n]
        l = left[i]
        r = right[i]
        res += n * (i - l + 1) * (r - i + 1)
        left[r+1] = l
        right[l-1] = r
    print(res)
    return


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
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: Accepted

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

b = [0] * (N + 1)
l = [i for i in range(N + 2)]
r = [i for i in range(N + 2)]

ans = 0
for i in range(N):
    b[a[i]] = i #各数字がaのどこに入っているかをリストbにメモ

for i in range(N, 0, -1):
    m = b[i] #大きな数字がどこに入っているかを探す
    x, y = l[m], r[m] #その時の左右に動ける大きさをとってくる
    ans += i * (m - x + 1) * (y - m + 1) #その数が何回使えるかを計算し、答えに追加
    l[y + 1], r[x - 1] = x, y #動ける範囲を次の場所に代入

print (ans)

Submission status: Accepted

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

P = [0]*N
for i,a in enumerate(A):
    P[a-1] = i

class UnionFind:
    def __init__(self,N):
        self.Parent = [-1]*N
        self.Min = [-1]*N
        self.Max = [-1]*N
    def get_Parent(self,n):
        if self.Parent[n] == -1:return n
        p = self.get_Parent(self.Parent[n])
        self.Parent[n] = p
        return p
    def get_min(self,n):
        p = self.get_Parent(n)
        return self.Min[p]
    def get_max(self,n):
        p = self.get_Parent(n)
        return self.Max[p]
    def merge(self,x,y):
        x = self.get_Parent(x)
        y = self.get_Parent(y)
        if x!=y: 
            self.Min[x] = min(self.Min[x],self.Min[y])
            self.Max[x] = max(self.Max[x],self.Max[y])
            self.Parent[y] = x
        return
    def is_united(self,x,y):
        return self.get_Parent(x)==self.get_Parent(y)
    def create(self,n):
        if self.Min[n] == -1:
            self.Min[n] = n
            self.Max[n] = n

T = UnionFind(N)
ans = 0
for i in range(N-1,-1,-1):
    p = P[i]
    T.create(p)
    if p-1>=0 and T.get_min(p-1)!=-1:
        T.merge(p,p-1)
    if p+1<N and T.get_min(p+1)!=-1:
        T.merge(p,p+1)
    ans += (i+1)*(p-T.get_min(p)+1)*(T.get_max(p)-p+1)
print(ans)

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    A = list(map(int, input().split()))
    pos = [-1] * (N+1)
    for i in range(N):
        pos[A[i]] = i
    left = list(range(N+2))
    right = list(range(N+2))
    ans = 0
    for i in range(N, 0, -1):
        p = pos[i]
        l = left[p]
        r = right[p]
        ans += i * (p-l+1) * (r-p+1)
        left[r+1] = left[p]
        right[l-1] = right[p]
    print(ans)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N = int(input())
*A, = map(int, input().split())
indices = {a: i for i, a in enumerate(A)}
left = {i: i for i in range(N)} # "left[i] = l" is equivalent to "A[l], ..., A[i-1] > A[i]"
right = {i: i for i in range(N)} # "right[i] = r" is equivalent to "A[i] < A[i+1], ..., A[r]"
ans = 0
for a in range(N, 0, -1):
    idx = indices[a]
    l, r = left[idx], right[idx]
    ans += (idx - l + 1) * (r - idx + 1) * a
    left[r+1], right[l-1] = l, r # A[l-1] < A[l], ..., A[r] > A[r+1]
print(ans)

Submission status: Accepted

Solution code:
n=int(input())
ans=0
arr=list(map(int,input().split()))
pos=[0]*(n+1)
for i in range(n):
  pos[arr[i]]=i
l=[i for i in range(n+1)]
r=[i for i in range(n+1)]
for i in range(n,0,-1):
  idx=pos[i]
  tl,tr=l[idx],r[idx]
  ans+=i*(idx-tl+1)*(tr-idx+1)
  l[tr+1]=tl
  r[tl-1]=tr
print(ans)

Submission status: Accepted

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

b = [[a[i],i] for i in range(N)]
b.sort(key=lambda x:x[0],reverse=True)

lr = [[0,0] for i in range(N)]
ans = 0
for i in range(N):
    ans+=b[i][0]*(lr[b[i][1]][1]+1)*(lr[b[i][1]][0]+1)
    if b[i][1]+lr[b[i][1]][1]+1<N:
        lr[b[i][1]+lr[b[i][1]][1]+1][0] = lr[b[i][1]][0]+lr[b[i][1]][1]+1
    if b[i][1]-lr[b[i][1]][0]-1>-1:
        lr[b[i][1]-lr[b[i][1]][0]-1][1] = lr[b[i][1]][0]+lr[b[i][1]][1]+1


print(ans)

Submission status: Accepted

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

index = [-1] * (n + 1)
for i, v in enumerate(a):
    index[v] = i

area = [[i, i] for i in range(n + 1)]
result = 0
for i in range(n, 0, -1):
    position = index[i]
    l, r = area[position]
    area[r + 1][0] = l # right
    area[l - 1][1] = r # left
    result += (position - l + 1) * (r - position + 1) * i
print(result)