Harryxun/sft_time huggingface dataset:
### BUGGY CODE ###

import sys
sys.setrecursionlimit(10**9)
input = lambda: sys.stdin.readline().rstrip()
inpl = lambda: list(map(int,input().split()))
N, M = inpl()
uv = [ set() for _ in range(N)]
vu = [ set() for _ in range(N)]
for _ in range(M):
    A, B = inpl()
    uv[A-1].add(B-1)
    vu[B-1].add(A-1)

for s in range(N):
    dfs_stack = [(s,set({}),set(range(N))-set({s}))]
    while dfs_stack:
        u, chain, remain = dfs_stack.pop()
        if s in uv[u] and len(chain):
            print(len(chain)+1)
            for c in chain:
                print(c+1)
            print(u+1)
            exit()
        else:
            new_remain = remain.copy()
            if u != s: new_remain -= vu[u]
            candidates = new_remain & uv[u]
            new_remain -= uv[u]
            new_chain = chain.copy()
            new_chain.add(u)
            for c in candidates:
                dfs_stack.append((c, new_chain, new_remain))
    for i in range(s+1,N):
        uv[i].discard(s)
print(-1)

### FIXED CODE ###

import sys
input = lambda: sys.stdin.readline().rstrip()
inpl = lambda: list(map(int,input().split()))
N, M = inpl()
uv = [ set() for _ in range(N)]
vu = [ set() for _ in range(N)]
for _ in range(M):
    A, B = inpl()
    uv[A-1].add(B-1)
    vu[B-1].add(A-1)

EMPTY, LOOP, TREE = 0, 1, 2
ENTER, EXIT = 0, 1
status = [EMPTY] * N
for s in range(N):
    states_pool = [(s,[],ENTER)]
    while states_pool:
        u, chain, flag = states_pool.pop()
        if flag == EXIT or status[u] == TREE:
            status[u] = TREE
            continue
        elif status[u] == LOOP:
            break
        else: # ENTER, EMPTY
            status[u] = LOOP
            states_pool.append((u,chain,EXIT))
            new_chain = chain.copy()
            new_chain.append(u)
            for c in uv[u]:
                states_pool.append((c, new_chain, ENTER))
    else:
        continue
    break
else:
    print(-1)
    exit()

n = 0
while chain[n] != u:
    n += 1
chain = chain[n:]
L = len(chain)
nextnode = [None]*N
for i in range(L-1):
    nextnode[chain[i]] = chain[i+1]
nextnode[chain[L-1]] = chain[0]
pos = [None]*N
for p in range(len(chain)):
    pos[chain[p]] = p
i = 0
while i < L:
    h = 1
    c = chain[(i+1)%L]
    for j in uv[chain[i % L]]:
        p = pos[j]
        if p is None:
            continue
        else:
            if (p-i)%L > h:
                h = (p-i)%L
                c = j
    nextnode[chain[i % L]] = c
    i += 1
    while chain[i % L] != c:
        pos[chain[i % L]] = None
        i += 1

loop = [c]
k = c
while nextnode[k] != c:
    k = nextnode[k]
    loop.append(k)
print(len(loop))
for l in loop:
    print(l+1)
### BUGGY CODE ###

n=int(input())
a=list(map(int,input().split()))
sum=0
for i in range(n):
    for j in range(i+1,n):
        if abs(i-j)==a[i]+a[j]:
            sum+=1
print(sum)

### FIXED CODE ###

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

add=[]
sub=[]
for i in range(n):
    add.append(i+a[i])
    sub.append(i-a[i])

add_dic={}
sub_dic={}

for l in add:
    if l in add_dic:
        add_dic[l]+=1
    else:
        add_dic[l]=1

for l in sub:
    if l in sub_dic:
        sub_dic[l]+=1
    else:
        sub_dic[l]=1

ans=0

for i,k in add_dic.items():
    if i in sub_dic:
        ans+=k*sub_dic[i]

print(ans)
### BUGGY CODE ###

def div(x, y): #x>y
    A = 1
    for i in range(1, x+1):
        if x % i == 0 and y % i == 0:
            A = i
    return A

x, y = map(int, input().split(" "))
print(div(x,y))





### FIXED CODE ###

import math
def div(x, y): #x>y
    A = 1
    for i in range(1, int(math.sqrt(x))+1):
        if x % i == 0 and y % i == 0:
            A = max(A, i)
        j = int(x/i)
        if x % j == 0 and y % j == 0:
            A = max(A, j)
    return A
x, y = map(int, input().split(" "))
print(div(x,y))
### BUGGY CODE ###

import math
from functools import reduce


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

maxi = math.pow(10,18)
mult = reduce(lambda x,y: x*y, A)
    
if mult > maxi:
    print("-1")
else:
    print(mult)


### FIXED CODE ###

N = int(input())
A = list(map(int, input().split()))
maxi = 10**18
def main():
    if 0 in A:
        print(0)
        return
    mult = 1
    for a in A:
        mult *= a
        if mult > maxi:
            print(-1)
            return 
    print(mult)

main()
### BUGGY CODE ###

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

for i,x in enumerate(Xs):
    arr = Xs[:i] + Xs[i+1:]
    arr.sort(reverse=True)
    m = int(N/2)-1
    print(arr[m])

### FIXED CODE ###

N = int(input())
Xs = list(map(int, input().split()))
s = sorted(Xs)
a = s[N//2-1]
b = s[N//2]
for x in Xs:
    if x < b:
        print(b)
    else :
        print(a)
### BUGGY CODE ###

N = int(input())
A = list(map(int, input().split()))
t = 0
for i in range(N):
    X = 0
    for j in range(N-i):
        X += A[i + j]
        if X == 0:
            t += 1

print(t)

### FIXED CODE ###

N = int(input())
A = list(map(int, input().split()))
B = {}
t = 0
x = 0
B[0] = 1
for i in A:
    x += i
    t += B.get(x, 0)
    B[x] = B.get(x, 0) + 1

print(t)
### BUGGY CODE ###

import heapq as h
n,q = map(int, input().split())
tl = []
que = []
d = dict()
for _ in range(n):
  s,t,x = map(int, input().split())
  h.heappush(tl,[s-x,1,x])
  h.heappush(tl,[t-x,0,x])
for _ in range(q):
  t = int(input())
  que.append(t)
  h.heappush(tl,[t,2])
wor = dict()
wcur = 0
cur = -1
for _ in range(n*2+q):
  x = h.heappop(tl)
  if x[1] == 1:
    wcur += 1
    wor[x[2]] = 1
    if cur < 0 or x[2] < cur:
      cur = x[2]
  elif x[1] == 0:
    wcur -= 1 
    wor[x[2]] = 0
    if cur == x[2]:
      if wcur:
        cur = min([x for x in wor if wor[x]])
      else:
        cur = -1
  else:
    d[x[0]] = cur
for i in que:
  print(d[i])

### FIXED CODE ###

def main():
    n,q = map(int, input().split())
    tl = []
    que = []
    d = dict()
    for _ in range(n):
        s,t,x = map(int, input().split())
        tl.append((s-x,1,x))
        tl.append((t-x,0,x))
    for _ in range(q):
        t = int(input())
        tl.append((t,2))
    tl.sort()
    wor = set()
    wcur = 0
    cur = -1
    flg = 0
    for x in tl:
        if x[1] == 1:
            wcur += 1
            wor.add(x[2])
            if cur < 0 or x[2] < cur:
                cur = x[2]
                flg = 0
        elif x[1] == 0:
            wcur -= 1 
            wor.remove(x[2])
            if x[2] == cur:
                flg = 1
            if not wcur:
                cur = -1
                flg = 0
        else:
            if flg:
                cur = min(wor)
                flg = 0
            print(cur)
    
if __name__ == "__main__":
    main()
### BUGGY CODE ###

A,B,C,K = map(int, input().split())
num = 0
ans = 0

if(A == K):
  print(A)
  exit()
if(A+B == K):
  print(A)
  exit()

for i in range(0,K):
  if(i < A):
    ans += 1
  elif(i < A+B):
    ans += 0
  else:
    ans -= 1
print(ans)

### FIXED CODE ###

A,B,C,K = map(int, input().split())
num = 0
ans = 0

if(A >= K):
  print(K)
elif(A < K and K <=(A+B)):
  print(A)
else:
  ans = A - (K-(A+B))
  print(ans)
### BUGGY CODE ###

N = int(input())
a = list(map(int,input().split()))
A = list(set(a))
c = 0
for i in range(len(A)):
    if a.count(A[i]) >= A[i]:
        c += a.count(A[i]) - A[i]
    elif a.count(A[i]) > 0:
        c += a.count(A[i])
print(c)


### FIXED CODE ###

N = int(input())
a = list(map(int, input().split()))
if N == 1:
    if a[0] != 1:
        print(1)
        exit()
    else:
        print(0)
        exit()
a.sort()
A = 0
c = 0
while True:
    try:
        #print(a)
        A = a[0]
        if len(a)>1:
            for i in range(1, len(a)):
                if a[i] != A:
                    # print(i + 1)
                    # c += i
                    del a[:i]
                    if i >= A:
                        c += i - A
                    else:
                        c += i
                    # print(a[i], c)
                    break
                elif i == len(a) - 1:
                    if i + 1 >= A:
                        c += i + 1 - A
                    else:
                        c += i + 1
                    print(c)
                    exit()
        else:
            print(c + 1)
            exit()
    except IndexError:
        break
### BUGGY CODE ###

# -*- coding: utf-8 -*-

import sys
from collections import deque

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 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

N = INT()
A = [deque()]
for i in range(N):
    A.append(deque(LIST()))

cnt = N*(N-1)//2
nxtli = list(range(1, N+1))
day = 0
while cnt > 0:
    prev = cnt
    skip = [False] * (N+1)
    # 前回変更があった場所のみでループを回す
    curli = nxtli[:]
    nxtli = []
    for i in curli:
        if len(A[i]) and not skip[i]:
            a = A[i][0]
            if len(A[a]) and not skip[a]:
                b = A[a][0]
                if i == b:
                    A[i].popleft()
                    A[a].popleft()
                    # 変更があった場所をリストに入れておく
                    nxtli += [i, a]
                    cnt -= 1
                    skip[i] = skip[a] = True
    if prev == cnt:
        print(-1)
        exit()
    day += 1
print(day)


### FIXED CODE ###

# -*- coding: utf-8 -*-

import sys
import time
from collections import deque

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 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

N = INT()
A = [deque()]
for i in range(N):
    A.append(deque(LIST()))

start = time.time()

cnt = N*(N-1)//2
day = 0
while cnt > 0:
    prev = cnt
    skip = [False] * (N+1)
    for i in range(1, N+1):
        if len(A[i]) and not skip[i]:
            a = A[i][0]
            if len(A[a]) and not skip[a]:
                b = A[a][0]
                if i == b:
                    A[i].popleft()
                    A[a].popleft()
                    cnt -= 1
                    skip[i] = skip[a] = True
    if prev == cnt:
        print(-1)
        exit()
    day += 1

    elapsed_time = time.time() - start
    if elapsed_time > 1:
        print(N*(N-1)//2)
        exit()
print(day)
### BUGGY CODE ###

from itertools import product


def solve(string):
    n, *a = map(int, string.split())
    a = sorted(a)
    if len(a) == 1:
        return "1"
    t = [True] * n
    for i, j in product(range(n), repeat=2):
        if i == j:
            continue
        if a[i] % a[j] == 0:
            t[i]=False
    return str(sum(t))


if __name__ == '__main__':
    import sys
    print(solve(sys.stdin.read().strip()))


### FIXED CODE ###

import numpy as np
from collections import Counter


def solve(string):
    n, *a = map(int, string.split())
    table = np.array([True] * (10**6 + 1))
    for _a in a:
        if table[_a]:
            table[2*_a::_a]=False
    i = np.array([k for k,v in Counter(a).items() if v==1],dtype=np.int)
    return str(table[i].sum())


if __name__ == '__main__':
    import sys
    print(solve(sys.stdin.read().strip()))
### BUGGY CODE ###

import math
import collections

def combinations_count(n, r):
    return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))

n = int(input())
li = list(map(int,input().split()))
c = list(collections.Counter(li).items())
ans = [0]*n
x = 0 #全てのボールから、できる組合せの総数

if len(c) == 1:
    ans = [combinations_count(n-1, 2)]*n
    print(*ans)
    exit()

for i in c:
    a = i[0]
    b = i[1]
    if b > 2:
        x += combinations_count(b, 2)
    elif b == 2:
        x += 1

for i in c:
    a = i[0]
    b = i[1]
    if b > 2:
        y = x - combinations_count(b, 2) + combinations_count(b-1, 2)
    elif b == 2:
        y = x - 1
    else:
        y = x
    ans[a-1] = y

for i in li:
    print(ans[i-1])

### FIXED CODE ###

import collections

def combinations_count(n, r):
    if n - r < r: r = n - r
    if r == 0: return 1
    if r == 1: return n

    numerator = [n - r + k + 1 for k in range(r)]
    denominator = [k + 1 for k in range(r)]

    for p in range(2,r+1):
        pivot = denominator[p - 1]
        if pivot > 1:
            offset = (n - r) % p
            for k in range(p-1,r,p):
                numerator[k - offset] /= pivot
                denominator[k] /= pivot

    result = 1
    for k in range(r):
        if numerator[k] > 1:
            result *= int(numerator[k])

    return result

n = int(input())
li = list(map(int,input().split()))
c = collections.Counter(li)
ans = [0]*n
x = 0 #全てのボールから、できる組合せの総数

if len(c) == 1:
    ans = [combinations_count(n-1, 2)]*n
    print(*ans)
    exit()

for i in c.items():
    a = i[0]
    b = i[1]
    if b > 2:
        x += combinations_count(b, 2)
    elif b == 2:
        x += 1

for i in c.items():
    a = i[0]
    b = i[1]
    if b > 2:
        y = x - combinations_count(b, 2) + combinations_count(b-1, 2)
    elif b == 2:
        y = x - 1
    else:
        y = x
    ans[a-1] = y

for i in li:
    print(ans[i-1])
### BUGGY CODE ###

N,K=map(int,input().split())
H=list(map(int,input().split()))
DP=[0]*(N)
DP[0]=0
DP[1]=abs(H[1]-H[0])
for i in range(2,N):
  DP[i]=min([abs(H[i]-H[k])+DP[k] for k in range(max(i-K,0),i)])
print(DP[N-1])

### FIXED CODE ###

def a():
    N, K = [int(n) for n in input().split()]
    h = [int(n) for n in input().split()]
    # dp[i]はi番目までたどり着くのに必要な最小コスト
    # dp[0] = 0
    # dp[1] = |h[1] - h[0]|
    # dp[i] = min(dp[0]+h[i]-h[0], dp[1]+h[i]-h[1], ...)
    dp = [0] * N
    dp[0] = 0
    dp[1] = abs(h[1] - h[0])
    for i in range(2, N):
        dp[i] = min([dp[k] + abs(h[k] - h[i]) for k in range(max(i - K, 0), i)])
    print(dp[N-1])
 
if __name__ == "__main__":
    a()
### BUGGY CODE ###

N, M = map(int,input().split())


def main():
	Ls = []
	Rs = []
	for i in range(M):
		inputs = list(map(int,input().split()))
		Ls.append(inputs[0])
		Rs.append(inputs[1])

	result = set()
	for i in range(1, M + 1):
		Li = Ls[i - 1]
		LiPlus = [j for j in range(Li + 1, Rs[i - 1] + 1)]
		if len(result) == 0:
			result = set([Li] + LiPlus)
		result = result & set([Li] + LiPlus)

	print(len(result))

if __name__ == '__main__':
	main()

### FIXED CODE ###

N, M = map(int,input().split())


def main():
	Ls = []
	Rs = []
	for i in range(M):
		inputs = list(map(int,input().split()))
		Ls.append(inputs[0])
		Rs.append(inputs[1])

	maxL = max(Ls)
	minR = min(Rs)

	if maxL > minR:
		print(0)
	else:
		print(minR - maxL + 1)

if __name__ == '__main__':
	main()
### BUGGY CODE ###

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

adic = {}
bdic = {}
cdic = {}

for i in range(len(a)):
    if a[i] in adic:
        adic[a[i]] = adic[a[i]] + 1
    else:
        adic.update({a[i]:1})

for i in range(len(b)):
    if b[i] in bdic:
        bdic[b[i]] = bdic[b[i]] + 1
    else:
        bdic.update({b[i]:1})
for i in range(len(c)):
    if c[i] in cdic:
        cdic[c[i]] = cdic[c[i]] + 1
    else:
        cdic.update({c[i]:1})



        
        
summer = 0
for j in bdic.keys():
    ai = 0
    ci = 0
    for i in adic.keys():
        if i < j:
            ai = ai + adic[i]
    for k in cdic.keys():
        if k > j:
            ci = ci + cdic[k]
    summer = summer + bdic[j] * ai * ci       
print(summer)
                
    
            

### FIXED CODE ###

N = int(input())
a = list(map(int,input().split(" ")))
b = list(map(int,input().split(" ")))
c = list(map(int,input().split(" ")))
#アルゴリズムわからないけどN log N?
a.sort()
b.sort()
c.sort()
 
#O(N)?
i,j,k = 0,0,0
ans = 0
while j < N:
  while i < N and a[i]<b[j] :
    i += 1
  while k < N and c[k]<=b[j]:
    k += 1
  ans += i * (N - k)
  j += 1
 

print(ans)
### BUGGY CODE ###

N = int(input())
a = list(map(int,input().split()))
total = sum(a)
ans = float('inf')
for i in range(1,N):
    ans = min(abs(total-2*sum(a[:i])),ans)
print (ans)


### FIXED CODE ###

N = int(input())
a = list(map(int,input().split()))
total = sum(a)
ans = float('inf')
x = 0
for i in range(N-1):
    x += a[i]
    ans = min(abs(total-2*x),ans)
print (ans)
### BUGGY CODE ###

n = int(input())
a = list(map(int,input().split()))
mod = 10**9+7
point = 0
for i in range(61):
    now = 0
    for j in a:
        now += (j >> i&1)
    now *= n-now
    now %= mod
    for k in range(i):
        now *= 2
        now %= mod
    point += now
    point %= mod
print(point)

### FIXED CODE ###

n = int(input())
a = list(map(int,input().split()))
mod = 10**9+7
point = 0
for i in range(61):
    now = 0
    for j in a:
        now += (j >> i&1)
    now *= n-now
    now %= mod
    for k in range(i):
        now *= 2
        now %= mod
    point += now
    point %= mod
print(point)
### BUGGY CODE ###

_,a=open(0)
t=1
for b in a.split():t*=int(b)
print(-~t*(t<=10**18)-1)

### FIXED CODE ###

n = int(input())
a = list(map(int, input().split()))
if 0 in a:
    print(0)
    exit()
ans = 1
for ai in a:
    ans *= ai
    if ans > 10**18:
        print(-1)
        break
else:
    print(ans)
### BUGGY CODE ###

from scipy.special import comb
import itertools

n, k = map(int, input().split())
x = list(map(int, input().split()))
X = []
m = 3*10**8

for v in itertools.combinations(x, k):
    X.append(list(v))

for i in range(comb(n, k, exact=True)):
    m0 = min(X[i])
    m1 = max(X[i])
    a = min(abs(m0)+abs(m1-m0), abs(m1)+abs(m1-m0))
    if m > a:
        m = a
print(m)

### FIXED CODE ###

n, k = map(int, input().split())
x = list(map(int, input().split()))
m = 3*10**8

for i in range(n-k+1):
    a = x[i]
    b = x[i+k-1]
    t= min(abs(a)+abs(b-a), abs(b)+abs(b-a))
    if m > t:
        m = t
print(m)
### BUGGY CODE ###

n, m, v, p = map(int, input().split())
a = sorted(list(map(int, input().split())))
if p >= v:
  print(sum([1 for b in a if b+m >= a[n-p]]))
else:
  s = p-1
  for i in range(n-p+1):
    if a[i]+m >= a[n-p] and (a[i]+m)*(n-p-i) - sum(a[(i+1):(n-p+1)]) >= (v-p-i)*m:
      s += 1
  print(s)

### FIXED CODE ###

n, m, v, p = map(int, input().split())
a = sorted(list(map(int, input().split())))
if p >= v:
  print(sum([1 for b in a if b+m >= a[n-p]]))
else:
  s = p-1
  t = sum(a[:(n-p+1)])
  for i in range(n-p+1):
    t -= a[i]
    if a[i]+m >= a[n-p] and (a[i]+m)*(n-p-i) - t >= (v-p-i)*m:
      s += 1
  print(s)
### BUGGY CODE ###

import sys
sys.setrecursionlimit(10000000)
MOD = 10 ** 9 + 7
INF = 10 ** 15
Dy = (-1,0,1,0)
Dx = (0,1,0,-1)

from collections import deque,defaultdict,Counter
def main():
    H,W,K = map(int,input().split())
    sy,sx,gy,gx = map(int,input().split())
    sy -= 1; sx -= 1; gy -= 1;gx -= 1
    pond = [list(input()) for _ in range(H)]
    
    q = deque([(sy,sx,-1)])
    dist = [[-1]*W for _ in range(H)]
    dist[sy][sx] = 0
    while q:
        oy,ox,turn = q.popleft()
        for i,dy,dx in zip(range(4),Dy,Dx):
            if i == turn:
                continue
            y,x = oy,ox
            for _ in range(K):
                y += dy
                x += dx
                if y < 0 or y >= H:
                    break
                if x < 0 or x >= W:
                    break
                if pond[y][x] == '@':
                    break
                if dist[y][x] >= 0:
                    continue
                dist[y][x] = dist[oy][ox] + 1
                q.append((y,x,(i + 2)%4))
                if (y,x) == (gy,gx):
                    break
    print(dist[gy][gx] if dist[gy][gx] >= 0 else -1) 
if __name__ == '__main__':
    main()

### FIXED CODE ###

import sys
sys.setrecursionlimit(10000000)
MOD = 10 ** 9 + 7
INF = 10 ** 15
Dy = (-1,0,1,0)
Dx = (0,1,0,-1)

from collections import deque,defaultdict,Counter
def main():
    H,W,K = map(int,input().split())
    sy,sx,gy,gx = map(int,input().split())
    sy -= 1; sx -= 1; gy -= 1;gx -= 1
    pond = [list(input()) for _ in range(H)]
    
    q = deque([(sy,sx)])
    dist = [[-1]*W for _ in range(H)]
    dist[sy][sx] = 0
    while q:
        ny,nx = q.popleft()
        for dy,dx in zip(Dy,Dx):
            y,x = ny,nx
            for _ in range(K):
                y += dy
                x += dx
                if y < 0 or y >= H:
                    break
                if x < 0 or x >= W:
                    break
                if pond[y][x] == '@':
                    break
                if dist[y][x] >= 0 and dist[y][x] <= dist[ny][nx]:
                    break
                if dist[y][x] < 0:
                    dist[y][x] = dist[ny][nx] + 1
                    q.append((y,x))
                if (y,x) == (gy,gx):
                    break
    print(dist[gy][gx] if dist[gy][gx] >= 0 else -1) 
if __name__ == '__main__':
    main()
### BUGGY CODE ###

import heapq as hp
from bisect import bisect_left

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

B = [0 for _ in range(N+1)]
for i, a in enumerate(A):
    B[a] = i+1

q = [0, N+1]
ans = 0
for n, b in enumerate(B):
    #print(q)
    if n == 0:
        continue
    im = bisect_left(q, b)
    L = q[im-1]
    R = q[im]
    #print(n, b, L, R)
    ans += (R-b)*(b-L)*n
    #print(ans)
    q.append(b)
    q.sort()

print(ans)

### FIXED CODE ###

from operator import itemgetter
import sys
input = sys.stdin.readline

# 二部探索木の代わり
# max_Xが大きい場合、0を含む場合は座標圧縮する

class BITbisect():
    def __init__(self, max_X):
        self.max_X = max_X + 1
        self.bit = [0]*(self.max_X+1)

    # x番目にaを加える
    def add(self, x, a):
        while x <= self.max_X:
            self.bit[x] += a
            x += x & -x

    def insert(self, x):
        self.add(x, 1)

    def delete(self, x):
        self.add(x, -1)

    # xまでに出現している個数
    def query_sum(self, x):
        s = 0
        while x > 0:
            s += self.bit[x]
            x -= x & -x
        return s

    def exist(self, x):
        if self.query_sum(x) - self.query_sum(x-1) > 0:
            return True
        return False
    
    def count(self, x):
        return self.query_sum(x) - self.query_sum(x-1)

    # xより大きくてbitに入ってるもののうち最小のもの
    # O((logN)^2)
    def upper(self, x):
        qx = self.query_sum(x) + 1
        if qx > self.query_sum(self.max_X):
            return False
        l = 0
        r = self.max_X
        while l < r:
            m = (l+r)//2
            if self.query_sum(m) < qx:
                if l == m:
                    return r
                l = m
            else:
                r = m
        if m == self.max_X:
            return False
        return m

    # x以下でbitに入っているもののうち最大のもの
    # O((logN)^2)
    def lower(self, x):
        qx = self.query_sum(x)
        if qx == 0:
            return False
        l = 0
        r = self.max_X
        while l < r:
            m = (l+r)//2
            if self.query_sum(m) < qx:
                if l == m:
                    return r
                l = m
            else:
                r = m
        return m

    # listみたいに表示
    def display(self):
        print('inside BIT:', end=' ')
        for x in range(1, self.max_X):
            if bit.exist(x):
                c = bit.count(x)
                for _ in range(c):
                    print(x, end=' ')
        print()


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

B = []
for i, a in enumerate(A):
    B.append((i+1, a))
B.sort(key=itemgetter(1))

bit = BITbisect(N)

ans = 0
for i, a in B:
    l = bit.lower(i)
    r = bit.upper(i)
    if l is False:
        l = 0
    if r is False:
        r = N+1
    ans += (i-l)*(r-i)*a
    bit.insert(i)
print(ans)