import sys import itertools read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines class BinaryIndexedTree(): def __init__(self, seq): self.size = len(seq) self.depth = self.size.bit_length() self.build(seq) def build(self, seq): data = seq size = self.size for i, x in enumerate(data): j = i + (i & (-i)) if j < size: data[j] += data[i] self.data = data self.history = [] def __repr__(self): return self.data.__repr__() def get_sum(self, i): data = self.data s = 0 while i: s += data[i] i -= i & -i return s def clear(self): for i in self.history: while i < self.size: self.data[i] = 0 i += i & -i self.history = [] def add(self, i, x): self.history.append(i) data = self.data size = self.size while i < size: data[i] += x i += i & -i def find_kth_element(self, k): data = self.data size = self.size x, sx = 0, 0 dx = 1 << (self.depth) for i in range(self.depth - 1, -1, -1): dx = (1 << i) if x + dx >= size: continue y = x + dx sy = sx + data[y] if sy < k: x, sx = y, sy return x + 1 N, *A = map(int, read().split()) U = 10 ** 5 ind = [[] for _ in range(U+1)] for i,x in enumerate(A): ind[x].append(i) def solve(N, I, bit0, bit1, bit2): if not I: return 0 def range_add(i,j): bit2.add(i, 1) bit1.add(i, -2*i+3) bit0.add(i, (i-1) * (i-2)) j += 1 bit2.add(j, -1) bit1.add(j, 2*j-3) bit0.add(j, -(j-1) * (j-2)) def range_sum(i,j): x = bit0.get_sum(j) + bit1.get_sum(j) * j + bit2.get_sum(j) * j * j i -= 1 x -= bit0.get_sum(i) + bit1.get_sum(i) * i + bit2.get_sum(i) * i * i return x ret = 0 x = N + 5 i = I[0] range_add(x-i,x) x -= i inv = 0 for i,j in zip(I, itertools.chain(I[1:], [N])): x += 1 # at i n = j - i inv += range_sum(x-n,x-1) range_add(x-n+1,x) x -= n - 1 return inv // 2 x = 0 bit0 = BinaryIndexedTree([0] * (N+N+10)) bit1 = BinaryIndexedTree([0] * (N+N+10)) bit2 = BinaryIndexedTree([0] * (N+N+10)) for I in ind: x += solve(N,I, bit0, bit1, bit2) bit0.clear() bit1.clear() bit2.clear() print(x)